Calendar

September 2010
S M T W T F S
« Jul    
 1234
567891011
12131415161718
19202122232425
2627282930  

Creating Grails Custom Constraints

Now and than there is the requirement to create custom constraints. As you might already know, there are plenty of constraints that already are shipped with Grails. Those can be applied in the constraints closure of your domain or command classes:

class User  {
String firstName
String surName
Short  age
static constraints = {
firstName(blank: false, maxSize: 150)
surName(blank: false, maxSize: 150)
age(min: 18 as Short, max: 99 as Short)
}
}

In order to implement custom constraints like i.e. an age constraint, which encapsulates the constraint’s implementation you could extend from Grail’s AbstractConstraint class. The problem with this approach is, that you than need to register your custom constraint at bootstrap, to use it in every possible scenario (going from testing to running the app).

Fortunately there is a plugin that helps with creating custom constraints: the constraints plugin.

grails install-plugin constraints

Installs the plugin and adds a dependency entry in your application or plugin settings. If installation was successful your grails help command lists the create-constraint command, that from now can be used to create custom constraints.

Creating an application-specific age constraint would be as simple as:

grails create-constraint Age

which creates grails-app/utils/AgeConstraint which i modified to be

class AgeConstraint {
def validate = { propertyValue ->
return propertyValue >= 18 && propertyValue <= 99
}
}

After declaring the constraint it can be used in domain or command classes:

class User  {
String firstName
String surName
Short  age

static constraints = {
firstName(blank: false, maxSize: 150)
surName(blank: false, maxSize: 150)
age(age: true)
}
}

If you take a look at the plugin’s documentation [0] there are several to use default message codes for i18n of error messages and so on. But this plugin works perfectly for adding custom constraints to your Grails environment.

[0] Constraints Plugin - http://github.com/geofflane/grails-constraints

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • Facebook
  • Google Bookmarks
  • Live
  • MySpace
  • PDF
  • RSS
  • Twitter
  • Yahoo! Bookmarks
  • email

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">