grailscommand-objects

Grails 2.5.0 - constraint be blank OR follow validation


I want to do something like:

class MyCommand {
     String name
     String data

     static constraints = {
         name blank: false, size: 3..64
         data (blank: true) || (blank: false, size: 3..64)
     }
}

where data is either blank or follows validation such as a size constraint if it is not blank. Is this possible to do without custom validation?


Solution

  • It would be non-trivial to use other constraints within a validator constraint. The delegate of the constraints closure is a ConstrainedPropertyBuilder, which you can read to understand the complexity.

    But that doesn't matter because the EmailConstraint uses Apache's EmailValidator, which you can use in your validator. Here's the EmailValidator in action:

    @Grab('commons-validator:commons-validator:1.4.1')
    
    import org.apache.commons.validator.routines.EmailValidator
    
    def emailValidator = EmailValidator.getInstance();
    
    assert emailValidator.isValid('what.a.shame@us.elections.gov')
    assert !emailValidator.isValid('an_invalid_emai_address')
    

    You can use EmailValidator in your own validator like this:

    import org.apache.commons.validator.routines.EmailValidator
    
    class MyCommand {
         String name
         String data
    
         static constraints = {
             name blank: false, size: 3..64
             data validator: {
                 if(it) {
                     EmailValidator
                         .getInstance()
                         .isValid(it)
                 } else { true }
             }
         }
    }