【发布时间】:2016-04-16 22:44:35
【问题描述】:
我在编辑用户时遇到了验证问题。一切正常,但每次我想编辑选定的用户时,我都会收到第二个密码(密码确认)为空的验证错误。我知道它是空的,因为我没有在我的数据库中存储密码确认。我的应用程序具有与 Grails 文档的 Spring Security Core 插件中几乎相同的 User 类,我没有更改默认 UserController 中的任何内容。
如何关闭该验证消息?
【问题讨论】:
我在编辑用户时遇到了验证问题。一切正常,但每次我想编辑选定的用户时,我都会收到第二个密码(密码确认)为空的验证错误。我知道它是空的,因为我没有在我的数据库中存储密码确认。我的应用程序具有与 Grails 文档的 Spring Security Core 插件中几乎相同的 User 类,我没有更改默认 UserController 中的任何内容。
如何关闭该验证消息?
【问题讨论】:
在您的情况下,它更依赖于您的业务逻辑。如果我假设您在创建页面上需要confirmPassword,但在编辑页面上不需要它,我会说使用CommandObjects。
从您的域中删除 confirmPassword。使用@Validatable annotation 创建一个命令对象。请在那里编写您的自定义验证以确认密码。根据您的需要进行调整。
此外,您可以为一个域拥有多个命令对象,或者我们可以说这些是独立于域的,可用于任何自定义验证或操作。
建议通过this 了解命令对象及其用法。
对于您的情况,co(简称)可能如下所示:
@Validatable
class UserCO {
def springSecurityService
String username
String password
String passwordConfirmation
boolean enabled = true
boolean accountExpired
boolean accountLocked
boolean passwordExpired
static constraints = {
username blank: false, unique: true
password blank: false, size: 5..60, password: true, display: false, validator: { val, obj ->
if (!obj.id && !obj.password) {
return 'validation.user.password'
}
}
passwordConfirmation bindable: true, blank: false, password: true, display: false, validator: { val, obj ->
if (obj.id && (!obj.password )) {
return true
}
if (!(obj.password == obj.passwordConfirmation)) {
return 'passwordMismatch'
}
return true
}
}
}
希望对你有帮助!
【讨论】:
您的域类中有 passwordConfirmation 字段并带有约束:
passwordConfirmation bindable: true, blank: false, password: true, display: false, validator: { val, obj ->
if (obj.id && (!obj.password )) {
return true
}
if (!(obj.password == obj.passwordConfirmation)) {
return 'passwordMismatch'
}
return true
}
它不能是“空白”,并且必须与“密码”相同。 所以,你有两种方法:
passwordConfirmation nullable: true
并手动启动迁移脚本或更新基础(需要删除非空约束)。【讨论】: