Reputation: 3907
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?
Upvotes: 1
Views: 104
Reputation: 9885
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('[email protected]')
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 }
}
}
}
Upvotes: 4