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:
class User {
...
static constraints = {
login shared: "myShared"
}
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:
String firstName
String lastName
String password
String confirmPassword
static constraints = {
importFrom User
password blank: false, nullable: false
confirmPassword blank: false, nullable: false
}
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':
...
static constraints = {
importFrom User, include: [/.*Name/]
...
Of course, exclude
does the reverse, specifying which constraints should not be imported.