Search code examples
grailsglobalsharedcustomvalidator

Grails custom validater, getting a reference to the field name


I am trying to write a generic custom validator for a property, to make it generic i need a reference to the field name within the closure, the code is as follows In config.groovy

grails.gorm.default.constraints = {
nameShared(validator: {val, obj, errors->
        Pattern p = Pattern.compile("[a-zA-Z0-9-]{1,15}")
        Matcher m = p.matcher(val)
        boolean b = m.matches()
        if(!b)
        errors.rejectValue('name', "${obj.class}.name.invalid", "Name is invalid")

    })

in My domain class

class Student{
  String name

  static constraints = {
       name(shared:'nameShared')
   }
}

class Teacher{
  String firstName
  String lastName

  static constraints = {
     firstName(shared:'nameShared')
  }
}

I want to use the same validator for both name and firstName, but since i am hardcoding the fieldName in the validator, it will always work for name and not firstName, so i want to know if there is anyway i can get a reference to the fieldname and make the validator generic, please help


Solution

  • You could use the variable propertyName to get the name of the validated property.

    From the grails docs:

    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" }