unit-testinggrailsgrails3grails-3.3

Custom validator name in grails 3


I am migrating a big project from grails 2.5.4 to 3.3.10. Everything is going well but I have a mayor problem in my domain objects. I use to write my custom validators this way:

class Person {
  String name

  static constraints = {
      name: nullable: false, validator: validateName
  }
  static validateName = {
      // validation code
  }
}

Grails throws the following exception

 No such property: validatorTest for class: org.grails.orm.hibernate.cfg.HibernateMappingBuilder

In grails 3.x this way of defining validators seems to be broken. I know the documentation says to use this way:

name nullable: false, validator: { // code }

But it is a LOT of code to rewrite in that case.

Is there a way to use the old method of defining validators?

Thanks


Solution

  • See the project at https://github.com/jeffbrown/alejandroveraconstraints.

    https://github.com/jeffbrown/alejandroveraconstraints/blob/master/grails-app/domain/alejandroveraconstraints/Person.groovy:

    // grails-app/domain/alejandroveraconstraints/Person.groovy
    package alejandroveraconstraints
    
    class Person {
        String name
    
        static constraints = {
            name nullable: false, validator: Person.validateName
        }
    
        static validateName = {
            it != 'Some Bad Name'
        }
    }
    

    https://github.com/jeffbrown/alejandroveraconstraints/blob/6701f61d61dbbde34f4925d1bf418448eee0a729/src/test/groovy/alejandroveraconstraints/PersonSpec.groovy:

    // src/test/groovy/alejandroveraconstraints/PersonSpec.groovy
    package alejandroveraconstraints
    
    import grails.testing.gorm.DomainUnitTest
    import spock.lang.Specification
    
    class PersonSpec extends Specification implements DomainUnitTest<Person> {
    
        void "test validation"() {
            expect:
            !new Person(name: 'Some Bad Name').validate()
            new Person(name: 'Some Good Name').validate()
        }
    }