Return Custom Validator Error Grails

血红的双手。 提交于 2019-12-06 04:49:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!