How to apply Constraints in Command Objects

Points To Remember

  • You need to add the @Validateable annotation to the command class.
  • Use importFrom in the constraints block with the domain name to import the constraints from domain.

How to add Constraints to the Command Object.

Lets us look at the example below. We have created a Domain by name User and a Command object by name UserCommand. We have created the constraints for email, password, first name and last name in User domain. We will import these constraints from domain to the command object and add some more constraints like verify password( if password and confirm password match).

User.groovy
package com.ekiras.domain

class User {

    String email
    String password
    String firstName
    String lastName

    static constraints = {
        email(nullable: false, blank: false, unique: true, email:true)
        password(nullable: false, blank: false)
        firstName(nullable: false, blank: false)
        lastName(nullable: false, blank: false)
    }

}

UserCommand.groovy
package com.ekiras.co

import com.ekiras.domain.User
import grails.validation.Validateable


@Validateable
class UserCommand {

    String email
    String password
    String firstName
    String lastName
    String confirmPassword
    static constraints = {
      // Imports the constraints of the User domain in UserCommand
        importFrom User  
        password minSize: 8, validator: {password, obj ->
            obj.confirmPassword == password ? true : 'Passwords do not match'
    }
}

You can now call the validate method over the UserCommand like userCommand.validate() and you can get the errors by calling userCommand.hasErrors() . This is how you can add constraints of the domain to the command objects or any other class.

No comments :

Post a Comment