我想确保检查表示布尔值的两个表单字段之一。但是没有适当的约束来做到这一点。nullable: false
不起作用。
class Organisation {
Boolean selfInspecting
static constraints = {
selfInspecting(nullable: false)
}
}
如何检查两个字段之一是否被选中?
我想确保检查表示布尔值的两个表单字段之一。但是没有适当的约束来做到这一点。nullable: false
不起作用。
class Organisation {
Boolean selfInspecting
static constraints = {
selfInspecting(nullable: false)
}
}
如何检查两个字段之一是否被选中?
也许最简单的方法是使用确保选择值的表单。因此,创建单选按钮而不是复选框是更好的解决方案。它也将直接代表您的意图。
您也可以在控制器中检查这一点,例如
if (params.checkBox1 != 'on' && params.checkBox2 != 'on')
flash.error = 'At least one value must be checked.'
return ...
您可以编写自己的自定义验证器。
就像是
selfInspecting(validator: {val, obj -> /*test selfInspecting here*/})
编辑——作为对另一个答案的回应——你可以在表单上处理它,但你也应该在服务器上处理它。
另一个编辑——在评论中建议您可能想要验证您的 Domain 类的两个字段之一。这也可以通过自定义验证器轻松完成。使用上面自定义验证器闭包的签名,val 是值 selfInspecting,obj 是域对象实例。所以你可以有
{ val, obj ->
if (val == null) return false // if you want to ensure selfInspecting is not null
else return true
... or ...
// if you want to check that at least 1 of two fields is not null
def oneOrTheOther = false
if (obj.field1 != null || obj.field2 != null)
oneOrTheOther = true
return oneOrTheOther
}