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"
  1. Create a groovy file in /grails-app/utils/ called *Constraint.groovy
  2. 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> result = neo4jTemplate.query("match (n:"+params.domainClass+") where n."+params.propertyName+" = '"+val+"' return n", null)
            for (Map m : result) {
                for (Map.Entry e : m.entrySet()) {
                    org.neo4j.kernel.impl.core.NodeProxy node =  e.getValue();
                    Long nodeId=node.getId()
                            return true
                    return  'default.not.unique.message'
            return true

    Apply the validation to a Domain class

    username size: 5..55, blank: false,


  3. 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

Request for Proposal

Recaptcha is required.

Sending message..