简体   繁体   English

Grails-命令对象,自定义条件验证器

[英]Grails - Command object, customized conditional validator

I would like to build a customized validator in my Command object, to make sure the field email address of a form will not be empty if the notifyMe checkbox is selected. 我想在Command对象中构建一个自定义的验证器,以确保如果notifyMe checkbox则表单的字段email address不会为空。

Here is my latest attempt to implement it: 这是我最近实现它的尝试:

email(blank: true, nullable: true, email: true,
                  validator: {email, creditProviderCommand ->
                              if (creditProviderCommand.notifyMe == 'on')
                                    return email.size() > 0})

I have tried also with email != null and email != '' but it is not working in both cases, meaning that the form submission is accepted even with the notifyMe checkbox checked and the email address field left blank. 我也尝试使用email != nullemail != ''但在两种情况下均不起作用,这意味着即使选中了notifyMe checkbox并且email address字段为空,也可以接受表单提交。

The code of the action handles the validation error properly (even unique constraint). 操作代码正确处理了验证错误(甚至是唯一约束)。 Any idea of what I am doing wrong ? 知道我在做什么错吗?

Thank you very much for your help. 非常感谢您的帮助。

The code above looks fine to me. 上面的代码对我来说很好。 Are you 100% sure that creditProviderCommand.notifyMe == 'on' when the checkbox is checked? 选中复选框后,您是否100%确定creditProviderCommand.notifyMe == 'on'

the form submission is accepted even with the notifyMe checkbox 即使使用notifyMe复选框,也可以接受表单提交

The form submission will always be accepted, even when there are validation errors. 即使存在验证错误,也将始终接受表单提交。 It is your responsibility to check for validation errors and decide what to do when validation fails, eg 您有责任检查验证错误并确定验证失败时应采取的措施,例如

def myAction = {MyCommand cmd ->

  if (cmd.validate()) {
    // code to be executed when validation succeeds
  } else {
    // code to be executed when validation fails
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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