【问题标题】:Grails - Command object, customized conditional validatorGrails - 命令对象,自定义条件验证器
【发布时间】:2011-09-05 11:19:52
【问题描述】:

我想在我的 Command 对象中构建一个自定义验证器,以确保在选择 notifyMe checkbox 时表单的字段 email address 不会为空。

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

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

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

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

非常感谢您的帮助。

【问题讨论】:

  • notifyMebooleanString 的类型是什么?实际赋予它什么值?我想booleanBoolean,所以你只需要检查它的真实性,而不是'on'

标签: grails validation constraints customvalidator command-objects


【解决方案1】:

上面的代码对我来说看起来不错。当复选框被选中时,您是否 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
  }
}

【讨论】:

  • 实际上有一个错误,Grails 允许仅包含空白字符的电子邮件(电子邮件约束)。这就是我解决这个问题的方法,使用 .trim() 排除空格:验证器:{email, creditProviderCommand -> if (creditProviderCommand.notifyMe) { if (!email) return email != null else return email.trim() != '' } }
猜你喜欢
  • 2013-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
相关资源
最近更新 更多