0

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

Alejandro Vera
  • 377
  • 2
  • 12

1 Answers1

2

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()
    }
}
Jeff Scott Brown
  • 26,804
  • 2
  • 30
  • 47
  • It worked great! It is very simple. I am amazed that this is necesary in grails 3. In deed, Intellij says me to remove the static reference, but it can't be done. Thanks again. And thanks for the sample project – Alejandro Vera Jun 11 '19 at 11:06
  • 2
    "I am amazed that this is necesary in grails 3." - Referring to an unqualified variable inside a Closure is generally problematic because you don't know what the `resolveStrategy` of the closure will be at execution time. `Person.validateName` would be more sensible even if `validateName` was allowed. – Jeff Scott Brown Jun 11 '19 at 13:42