Archive

Archive for the ‘constraints’ Category

Creating 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

Advertisements
Categories: constraints, grails