(Quick Reference)



Adds custom validation to a field.


even validator: {
    return (it % 2) == 0

password1 validator: { val, obj -> obj.password2 == val }

magicNumber validator: someClosureWithTwoParameters

// This one assumes you have an error message defined like // this (wrapped here only for display purposes): // classname.propertyName.custom.error= My error shows arguments {3} and {4} for value {0} otherProperty validator: { return ['custom.error', arg1, arg2] }

// The following example does not use custom validation. // A custom message may be defined in messages.properties: // user.username.blank=Please enter a username // which will be used instead of default.blank.message class User {

String username

static constraints = { username blank: false } }

// In the following example, custom validation is used: // user.username.validator.invalid=Please enter a username class User {

String username

static constraints = { username validator: { return it.length != 0 } } }

// The following might define the error message as: // user.username.invalid.bountyhunter=Invalid bounty hunter ({2}) tried to log in. class User {

String username

static constraints = { username validator: { if (!it.startsWith('boba')) return ['invalid.bountyhunter'] } } }


A custom validator is implemented by a Closure that takes up to three parameters. If the Closure accepts zero or one parameter, the parameter value will be the one being validated ("it" in the case of a zero-parameter Closure). If it accepts two parameters the first is the value and the second is the domain class instance being validated. This is useful when your validation needs access to other fields, for example when checking that two entered passwords are the same. If it accepts three parameters the first is the value, the second is the instance, and the third is the Spring Errors object.

The closure can return:

  • null or true (or no return value) to indicate that the value is valid
  • false to indicate an invalid value and use the default message code
  • a string to indicate the error code to append to the "classname.propertName." string used to resolve the error message. If a field-specific message cannot be resolved, the error code itself will be resolved allowing for global error messages.
  • a list containing a string as above, and then any number of arguments following it, which are used as formatted message arguments indexed at 3 onwards. See grails-app/i18n/message.properties to see how the default error message codes use the arguments.

In the case of a three-parameter Closure the return value is ignored since it is expected the the Errors object will be updated directly.

The Closure also has access to the name of the field that the constraint applies to using propertyName:

myField validator: { val, obj -> return propertyName == "myField" }

Error Code: className.propertyName.validator.error