【发布时间】:2015-10-04 20:14:30
【问题描述】:
环境:Grails 2.3.8
我要求用户的密码可以为空,但不能为空。 所以我这样定义域:
class User{
...
String password
static constraints = {
...
password nullable:true, blank: false
}
}
我为约束写了一个单元测试:
void "password can be null but blank"() {
when: "create a new user with password"
def user = new User(password: password)
then: "validate the user"
user.validate() == result
where:
password | result
"hello" | true
"" | false
null | true
}
"hello" 和 null 情况都很好,但空白字符串 ("") 失败: junit.framework.AssertionFailedError:条件不满足:
user.validate() == result
| | | |
| true | false
| false
app.SecUser : (unsaved)
at app.UserSpec.password can be null but blank(UserSpec.groovy:24)
- 是否可以为空覆盖空白:假?
- 我知道我可以使用自定义验证器来实现需求,我很好奇有没有更好的方法?
- 我做错了吗?
【问题讨论】:
-
哪个版本的 grails?部分版本通过数据绑定将Blank改为null。
-
我使用的是 Grails 2.3.8。正如@Jeff Scott Brown 的回答确实解决了我的问题。我认为您的方向也是正确的。所以你的意思是在其他版本中,我的问题不会有问题,对吧?
-
在旧版本中并非如此。我不记得这是从什么时候开始的。但是,是的,我说的和 Jeff 说的一样。
-
在 Grails 2.3 中引入了将空白字符串转换为 null 的功能。见grails.github.io/grails-doc/2.3.0/guide/…。
标签: grails grails-domain-class