I have a Grails domain class. I would like to add a validation such that when the application is running in TEST environment, the domain class can't have more than 100 records.
I can't figure out the best way to add this type of validation. I am on Grails 2.5.3.
This is what I have so far.
class MyDomain {
String test
static constraints = {
test blank: false, nullable: false
id blank: false, validator: {value, command ->
if (Environment.current == Environment.TEST) {
//do validation for not allowing more than 100 records
}
}
}
How can I add this validation?
Solution for a single domain
What @Joshua answered is perfectly fine but there are few other ways. One of them is:
Also, please note two things:
blank: false
on theid
field of no use since it is not a string becauseblank
constraint is applicable on a Stringnullable: false
is of no use since the default value ofnullable
constraint isfalse
Generic solution for across domain TL;DR
If you want this behavior across multiple domains, copying the same code is not recommended as your code won't be DRY. For that, you can register a custom event listener:
First define a Java annotation in
src/groovy
:Now define another Groovy class:
Now register this in
Bootstrap.groovy
:Now, in your domain, all you have to do is like these: