Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Grails Goodness: Combining Constraints with Shared Constraints

DZone's Guide to

Grails Goodness: Combining Constraints with Shared Constraints

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

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 propertygrails.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:

1. // File: grails-app/conf/Config.groovy
2. ...
3. grails.gorm.default.constraints = {
4.     // New constraint 'customEmail'.
5.     customEmail(maxSize: 256, email: true)
6. }
7. ...

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 constraintsconfiguration. 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.

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}