Create custom domain Constraints for validating Domain objects
Posted By : Abhay Garg | 23-Dec-2014
This Blog is for creating the Custom Constraints Validation for Domain .
Purpose -> This type of requirements come in any situation like in our project , We use Neo4j database and Spring Data Neo4j , So unique constraints that grails Plugin provide we cannot use because SDN does not provide any type of Constraints . So we have to implement Custom Validator.
Plugin use -
compile ":constraints:0.8.0"
- Create a groovy file in /grails-app/utils/ called *Constraint.groovy
- Implement a validate closure
Ex ->class UniqueUserConstraint { //static name ="uniqueName" static expectsParams = true static defaultMessageCode = "default.not.unique.message" def neo4jTemplate /* * This validation is for checking unique , it work in all cases * for saving , update anything */ def validate = { val ,target-> Result
Apply the validation to a Domain class
username size: 5..55, blank: false,
uniqueUser:['domainClass':'User','propertyName':'username']
-
We have username as a Property in our Database , you can use this constraints anywhere in your code , just pass the correct parameter Domain class , propertyname is username , if you want to use unique constraints on email then propertName should be 'email'
For more information use this link Custom Validation
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Abhay Garg
Abhay is a Grails Developer expertise in OptaPlanner and Angular js framework.