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

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

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.

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

Topics:

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}