Over a million developers have joined DZone.

Grails Goodness: Combining Constraints with Shared Constraints

DZone's Guide to

Grails Goodness: Combining Constraints with Shared Constraints

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

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

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.

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.


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

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}