In addition to defining constraints in domain classes, command objects and , you can also define them in :

    These constraints are not attached to any particular classes, but they can be easily referenced from any validateable class:

    1. class User {
    2. ...
    3. static constraints = {
    4. login shared: "myShared"
    5. }

    Note the use of the shared argument, whose value is the name of one of the constraints defined in grails.gorm.default.constraints. Despite the name of the configuration setting, you can reference these shared constraints from any validateable class, such as command objects.

    Importing Constraints

    Grails 2 introduced an alternative approach to sharing constraints that allows you to import a set of constraints from one class into another.

    Let’s say you have a domain class like so:

    You then want to create a command object, UserCommand, that shares some of the properties of the domain class and the corresponding constraints. You do this with the importFrom() method:

    1. String firstName
    2. String lastName
    3. String password
    4. String confirmPassword
    5. static constraints = {
    6. importFrom User
    7. password blank: false, nullable: false
    8. confirmPassword blank: false, nullable: false
    9. }

    If you want more control over which constraints are imported, use the include and exclude arguments. Both of these accept a list of simple or regular expression strings that are matched against the property names in the source constraints. So for example, if you only wanted to import the 'lastName' constraint you would use:

    or if you wanted all constraints that ended with 'Name':

    1. ...
    2. static constraints = {
    3. importFrom User, include: [/.*Name/]
    4. ...

    Of course, exclude does the reverse, specifying which constraints should not be imported.