简体   繁体   中英

Custom domain constraint in grails

public class Service {

    String reviewChanges
    String comment

    static constraints = {
      reviewChanges (inList:['NO','YES'])
      comment validator: { val, obj ->
        if(reviewChanges=='YES') {
          (nullable:false, blank:false, minSize:1, maxSize:500)
        } else {
          (nullable:true, blank:true, minSize:1, maxSize:500)
        }
      }
    }
}

Above comment validator does not work for me. I want if reviewChanges field selected YES then Comment field must be Mandatory field else Comment filed Non-Mandatory

The best way working with custom validators would be like this..

static constraints = {
    reviewChanges(inList:['NO','YES'])
    comment validator: { val, obj,errors ->
        if (obj.reviewChanges == 'YES' && StringUtils.isEmpty(val))  { 
            errors.rejectValue('comment',"some.custom.validation.key")
        }
    }
}

errors.rejectValue will allow you to give proper field errors using propertyName and also you can use it for parameterized error...

errors.rejectValue('propertyName','errorCode',errorArgs as Object[],'defaultMessage')

and define errorCode is message.properties to access errorArgs like

errorCode = This is {0} first parameter being passed as errorArgs.

Thanks

You could do something like this I think (I haven't tested this, but you get the idea):

static constraints = {
    reviewChanges(inList:['NO','YES'])
    comment validator: { val, obj ->
        if (obj.reviewChanges == 'YES' && StringUtils.isEmpty(val))  { 
            return "some.custom.validation.key"
        }
    }
}

Unless there is a requirement to have reviewChanges as a String, I would make it a Boolean field and using Groovy truth, you should be able to do something like:

class Service {

    Boolean reviewChanges
    String comment

    static constraints = {
       comment nullable:true, minSize:1, maxSize:500, validator: { val, obj ->
          if (obj.reviewChanges && (!val)){
             return "comments.required"
          }
       }
    }

}

using Grails 2.3.3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM