12.6 Applying Validation to Other Classes

Domain classes and Command Objects support validation by default. Other classes may be made validateable by defining the static constraints property in the class (as described above) and then telling the framework about them. It is important that the application register the validateable classes with the framework. Simply defining the constraints property is not sufficient.

The Validateable Trait

Classes which define the static constraints property and implement the Validateable trait will be validateable. Consider this example:

src/main/groovy/com/mycompany/myapp/User.groovy

  1. package com.mycompany.myapp
  2. import grails.validation.Validateable
  3. class User implements Validateable {
  4. ...
  5. static constraints = {
  6. login size: 5..15, blank: false, unique: true
  7. password size: 5..15, blank: false
  8. email email: true, blank: false
  9. age min: 18
  10. }
  11. }
Programmatic access

Accessing the constraints on a validateable object is slightly different. You can access a command object’s constraints programmatically in another context by accessing the constraintsMap static property of the class. That property is an instance of Map<String, ConstrainedProperty>

In the example above, accessing User.constraintsMap.login.blank would yield false, whileUser.constraintsMap.login.unique would yield true.