Search code examples
groovyconstraintsmaxlength

Add constraints to properties of Groovy class (not Grails domain class!)



How can we add some common constraints (i.e. maxLength, nullable) to a property of a Groovy class? I know we can do it at Grails domain class, but is it possible if that is a Groovy class (I use it as a DTO class for my Grails project)?
Thank you so much!


Solution

  • You can add constraints to command classes. If a command class is in the same .groovy file as a controller (in Groovy you can have more than one public class in each .groovy file), you don't need to do anything special for Grails to recongise it as a command class.

    However, if your command class is somewhere else (e.g. under src/groovy), you need to annotate it with @Validateable and add the package name to the grails.validateable.packages parameter in Config.groovy. Here's an example of a command that's not in the same file as a controller

    pacakge com.example.command
    
    @Validateable
    class Person {
      Integer age
      String name
    
      static constraints = {
        name(blank: false)
        age(size 0..100)
      }
    }
    

    Add the following to Config.groovy

    grails.validateable.packages = ['com.example.command']
    

    Command classes have a validate() method added by Grails. After this method is called, any errors will be available in the errors property (as per domain classes).