Grails command object temporary field validation

江枫思渺然 提交于 2019-12-12 02:33:56

问题


I have a user registration form where the fields are validated using command object. One of the fields is a checkbox, which must checked before proceeding the registration, and it isn't saved to the domain object. This checkbox has a corresponding Boolean field in the command object. When checkbox is not checked, a validation error is thrown from a custom validator.

The problem is, that this error is not propagated in the <g:renderErrors bean="${command}" as="xml"/> block (the validator is fired correctly).

The command object:

class RegisterCommand {

...
Boolean termsChecked
...
static constraints = {
    ...
    termsChecked validator: RegisterController.termsCheckedValidator
}

Validator:

static final termsCheckedValidator = {termsChecked, command, errors ->
    if (!command.termsChecked) {
        return 'registerCommand.termsChecked.required'
    }
}

Checkbox in the GSP file:

<g:checkBox value="${command.termsChecked}" bean="${command}" name='termsChecked'/>

How this could be solved?


回答1:


If you pass 3 parameters to the validator with the last one being errors then the return code is ignored thinking that the Spring Errors is taking care of errors.

If you want to use the error code then just pass 2 parameter to the validator as

static final termsCheckedValidator = {termsChecked, command ->
    if (!command.termsChecked) {
        return ['required.termsChecked']
    }
}


//messages.properties
registerCommand.termsChecked.required.termsChecked=blah


来源:https://stackoverflow.com/questions/19292466/grails-command-object-temporary-field-validation

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