Search

Dark theme | Light theme

March 17, 2014

Grails Goodness: Combining Constraints with Shared Constraints

In our Grails applications we might have fields that need the same combination of constraints. For example we want all email fields in our application to have a maximum size of 256 characters and must apply to the email constraint. If we have different classes with an email field, like domain classes and command objects, we might end of duplicating the constraints for this field. But in Grails we can combine multiple constraints for a field into a single constraint with a new name. We do this in grails-app/conf/Config.groovy where we add the configuration property grails.gorm.default.constraints. Here we can define global constraints with can be used in our Grails application.

Let's add a custom email constraint in our application:

// File: grails-app/conf/Config.groovy
...
grails.gorm.default.constraints = {
    // New constraint 'customEmail'.
    customEmail(maxSize: 256, email: true)
}
...

To use the constraint in a domain class, command object or other validateable class we can use the shared argument for a field in the constraints configuration. Suppose we want to use our customEmail constraint in our User class:

// File: src/groovy/com/mrhaki/grails/User.groovy
package com.mrhaki.grails.User

@grails.validation.Validateable
class User {
    String username
    String email

    static constraints = {
        // Reference constraint from grails.gorm.default.constraints
        // with shared argument.
        email shared: 'customEmail'
    } 
}

Code written with Grails 2.3.7.