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

发布于 2024-12-03 03:34:06 字数 617 浏览 1 评论 0原文

我想在我的 Command 对象中构建一个自定义验证器,以确保在选中 notifyMe 复选框 时,表单的电子邮件地址 字段不会为空。

这是我实现它的最新尝试:

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

我也尝试过 email != nullemail != '' 但在这两种情况下都不起作用,这意味着即使选中了 notifyMe 复选框 并且电子邮件地址 字段留空,表单提交也会被接受。

操作的代码正确处理验证错误(甚至是唯一约束)。 知道我做错了什么吗?

非常感谢您的帮助。

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.

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

英雄似剑 2024-12-10 03:34:06

上面的代码对我来说看起来不错。当选中该复选框时,您是否 100% 确定 creditProviderCommand.notifyMe == 'on'

即使带有notifyMe复选框,表单提交也会被接受

即使存在验证错误,表单提交也将始终被接受。您有责任检查验证错误并决定验证失败时该怎么做,例如

def myAction = {MyCommand cmd ->

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

The code above looks fine to me. Are you 100% sure that creditProviderCommand.notifyMe == 'on' when the checkbox is checked?

the form submission is accepted even with the notifyMe checkbox

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, e.g.

def myAction = {MyCommand cmd ->

  if (cmd.validate()) {
    // code to be executed when validation succeeds
  } else {
    // code to be executed when validation fails
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文