Applying Validation Constraints in Classes other than Domain classes and Command Objects
We usually specify validation constraints in domain classes and command objects.
But, if it is required to provide validation in other classes(like classes in src/groovy), we can do so in two ways :
1. Defining a static constraints property in the class and using the @validateable annotation.
2. Defining a static constraints propery in the class and making an entry of the class in grails.validateable.classes property in config.groovy.
Here is an example of first way:
[java]
package com.example.dto
import grails.validation.Validateable
@Validateable
class DataDTO {
String site
Integer views
static constraints = {
site blank: false
views blank: false
}
}
[/java]
If a class is not marked with @Validateable, it may still be made validateable by defining the static constraints property in the class (as shown above) and then assigning class name(with package name) to the grails.validateable.classes property in Config.groovy:
[java]
grails.validateable.classes = [com.example.dto.DataDTO]
[/java]
In older versions of grails, one could achieve the same result in a slightly different way as mentioned here.
Hope it helps 🙂
Raj Gupta
raj.gupta@intelligrape.com
@rajdgreat007
Hi Thomas,
You are correct. Grails will not be able to check for the uniqueness of site property since the class is not bound to any database. I corrected it in my example. Thanks for pointing out.
Nice. Thank you for that. 🙂
I have one question:
In your specific example in what context is the site-property of an object of the class DataDTO unique? Since the class is not bound to any database table does grails check if the site-property of all instaces is unique?
Thomas