Reputation: 1
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
Upvotes: 0
Views: 893
Reputation: 697
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
Upvotes: 1
Reputation: 1543
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
Upvotes: 0
Reputation: 3694
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"
}
}
}
Upvotes: 0