问题
I'm only getting the default validator message. What am I doing wrong?
class Questao {
static hasMany = [alternativas:Alternativa]
static constraints = {
alternativas (validator: {val, obj ->
if(val.size() < 2)
return ['validator.message'] //custom message
})
}
}
/i18n
questao.alternativas.validator.message = "must be greater than two"
default.invalid.validator.message= Property [{0}] of class [{1}] with value [{2}] does not pass custom validation
Thanks
回答1:
You're returning a list containing your message code - you need to return just the code:
alternativas validator: { val, obj ->
if (val.size() < 2) {
return 'validator.message' //custom message
}
}
回答2:
This API has changed. Returning a string with a custom error message will no longer work. Unfortunately, this is not well-documented.
Returning a string or a non-empty list will evaluate to true
according to the Groovy Truth. Which means, the validator signals, "accepted". - Either return false
, or, if you need a custom error message, explicitly rejectValue(..)
the value:
alternativas (validator: {val, obj ->
if(val.size() < 2)
obj.errors.rejectValue('alternatives',
'questao.alternativas.validator.message')
})
回答3:
Additionally:
In Grails 2.5.2 (I only tested in this version) if you use the errors argument in the custom validator closure and return a message code (or an array with the message code) it does not work, you need to use directly the errors object to put the message code.
来源:https://stackoverflow.com/questions/4111880/return-custom-validator-error-grails