Grails Custom Validator Snippets

This post is going to be updated on-going and is a space where i hope to collect different examples of custom validators that ensure  some constraint for a Domain class in Grails Framework

1. Ensure specific Date format constraint (i.e. ‘Jan 22, 2011’)

String submitDate 
...
final static DateFormat DATEFORMAT  = DateFormat.getDateInstance(DateFormat.MEDIUM)
static constraints = {
      submitDate validator: {
         try{
             Date date = DATEFORMAT.parse(it)
             return DATEFORMAT.format(date) == it
         }catch(ParseException exception){
             return false
         }
      }

2. Zip Code validator

static constraint = {
   zipCode blank: false, size: 5..10, validator:{zip ->
            (zip ==~ /^(\d{5}-\d{4})|(\d{5})$/) ? true : false
        }
}

3. Numeric validator for Phone number,Social Security number,etc
a) If you know exactly how many numbers should contain. Here is example for 10:

static constraints = {
     ...
        phone matches: '\\d{10}'
     ...
    }

b) If its necessary to validate for some specific pattern such as 651-555-5555

static constraints = {
     ...
        phone matches: '\\d{3}\\-\\d{3}\\-\\d{4}'
     ...
    }

c)If its necessary to validate that it contains only numbers

static constraints = {
     ...
        phone matches: '\\d+'
     ...
    }

Leave a Reply

Your email address will not be published. Required fields are marked *