Custom Validators in Grails in a Single App

by Geoff Lane on January 26th, 2008

In my previous post I wrote about Building a Custom Validator in Grails using a Plugin. That’s a great way to build a reusable Constraint that will allow you to share your code among multiple projects. But often you only have one application that you are building, or a validator is a very domain specific thing that will only make sense in a single app.

Building the Constraint in a Single App

Please look at the previous post for the details of the Plugin.
As I mentioned in that post a plugin looks almost exactly like a Grails App. Just like in the plugin case, your grails app has a src/groovy and a src/java directory where you can put general code. In this case I wrote the Constraint in the src/groovy directory as I wanted to use the Groovy language and some of the fun dynamic techniques it offers.

Hook it into the App

Here’s the simple part. The goal, as we saw in the plugin example, is to register your custom Constraint with the Grails ConstrainedProperty class. I just took a guess on this one and it worked. Grails provides the
Config.groovy class to setup a bunch of things in your application. So all you need to do is add the ConstraintProperty configuration to your Config.groovy script and your application will have a new constraint:

Config.groovy


org.codehaus.groovy.grails.validation.ConstrainedProperty.registerNewConstraint(
    PostalCodeConstraint.POSTAL_CODE_CONSTRAINT, PostalCodeConstraint.class)

Have fun building your own Constraints!

From → Code, Groovy

3 Comments
  1. hey man, this is awesome thanks.

  2. uday permalink

    Hey, i tried to go through your examples but come across this issue:
    No signature of method: static org.codehaus.groovy.grails.validation.ConstrainedProperty.registerNewConstraint() is applicable for argument types

    this happens when i add:
    org.codehaus.groovy.grails.validation.ConstrainedProperty.registerNewConstraint(PhoneNumberConstraint.PHONE_NUMBER_CONSTRAINT, PhoneNumberConstraint.class) to the Config.groovy class.

    Any idea how i could get past it…?
    thanks!

Trackbacks & Pingbacks

  1. hilderclan.de/blog » Blog Archive » custom constraints in grails

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS