12.2 Validating Constraints

Validation Basics

Call the validate method to validate a domain class instance:

  1. def user = new User(params)
  2. if (user.validate()) {
  3. // do something with user
  4. }
  5. else {
  6. user.errors.allErrors.each {
  7. println it
  8. }
  9. }

The errors property on domain classes is an instance of the Spring Errors interface. The Errors interface provides methods to navigate the validation errors and also retrieve the original values.

Validation Phases

Within Grails there are two phases of validation, the first one being data binding which occurs when you bind request parameters onto an instance such as:

  1. def user = new User(params)

At this point you may already have errors in the errors property due to type conversion (such as converting Strings to Dates). You can check these and obtain the original input value using the Errors API:

  1. if (user.hasErrors()) {
  2. if (user.errors.hasFieldErrors("login")) {
  3. println user.errors.getFieldError("login").rejectedValue
  4. }
  5. }

The second phase of validation happens when you call validate or save. This is when Grails will validate the bound values against the constraints you defined. For example, by default the save method calls validate before executing, allowing you to write code like:

  1. if (user.save()) {
  2. return user
  3. }
  4. else {
  5. user.errors.allErrors.each {
  6. println it
  7. }
  8. }