Tuesday 23 June 2009

Custom constraint

The other day we were doing some refactoring and we started to look into how all our validation is done. We noticed that we have a lot of duplication in our validators and wanted to do something about it. We came across the following blog post that describes how to create a custom validator. This is a great little blog post and allowed us to kill a lot code.

One thing that we did notice was that they suggest that you put the registering of the custom validator in the Config.groovy file. We found this problematic and found that the better solution was to put it in the resources.groovy file. Another problem that we came across was that you needed to register the constraint in the unit test if you wanted to be able to test constraints. This makes sense because resources.groovy isn't called in unit tests.

To register your constraint use the following line of groovy code:
ConstrainedProperty.registerNewConstraint(PhoneNumberConstraint.NAME, PhoneNumberConstraint)

Hopefully this helps with some refactoring.
Glenn

1 comment:

Rob said...

Once we start using more than one we could introduce a CustomConstraintRegistrar bean that is placed in resources.groovy and just registers all the constraints in its init method. That's the mechanism Grails uses for custom property binders. Then we could run that in _Events.groovy when the unit test phase starts.