Announcing Grails Constraints Custom Domain Constraint Plugin

October 26, 2009 - 2 minute read -
grails plugins validation

I've released my first public Grails Plugin today.

The Grails Constraint plugin gives you the ability to create custom Constraints that you can apply to your Domain classes to validate them. These are applied and act just like the built in Domain class constraints.

Why would you want this?

Grails provides two generic, catch-all Constraints in the core application:

  • validator - a generic closure mechanism for validation
  • matches - a regular expression mechanism

While those work, I find myself often wanting to use the same Constraints on multiple Domain classes (think Social Security Number, Phone Number, Zipcode, etc.) and I don't like to repeat those regular expressions or validations all over the place.

What does this plugin do?

With the Grails Constraints plugin, you can write a custom Constraint class, drop it in /grails-app/utils/ and it will automatically be available to all of your domain classes.


I create a new constrain by hand in /grails-app/utils/ComparisonConstraint.groovy. (You can also use the provided create-constraint script like grails create-constraint

class ComparisonConstraint {
    static name = "compareTo"
    static expectsParams = true
    def validate = { val, target ->
        def compareVal = target."$params"
        if (null == val || null == compareVal)
            return false
        return val.compareTo(compareVal) == 0

Then you can apply your constraint to your Domain class:

class Login {
    String password
    String confirm
    static constraints = {
        password(compareTo: 'confirm')

See Grails Custom Constraints Plugin for the full documentation on what all of the above means and the source code.