Custom Validators in Grails in a Single App

January 26, 2008 - 2 minute read -
groovy grails validation

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!