我想在我的项目的注册页面中添加密码确认。但我对我的一个领域的价值有疑问。所有字段都可以,但 password2 字段是确认密码,是 User 域类的临时字段。这是我的域、控制器和视图代码
领域类:
class User {
String fullName
String username
String email
String password
String password2
static transients = ['password2']
static constraints = {
username size: 5..15, blank: false, unique: true
email email: true, blank: false
password blank:false, size:5..15, matches:/[\S]+/, validator:{ val, obj ->
if (obj.password != obj.password2)
return 'user.password.dontmatch'
}
}
}
控制器的一部分:
if (request.method == 'POST') {
// create domain object and assign parameters using data binding
def u = new User(params)
if (! u.save()) {
// validation failed, render registration page again
flash.error = "error(s) creating user: Value of the confirmation password is: "+u.password2
//render(view:"/signup",model:[user:user])
return [user:u]
} else {
// validate/save ok, store user in session, redirect to homepage
session.user = u
redirect(controller:'home')
return
}
} else if (session.user) {
// don't allow registration while user is logged in
redirect(controller:'home')
return
}
以及视图的一部分:
<div><input class="pretty-input ${hasErrors(bean:user,field:'email','input-error')}" type="email" name="email" value="${user?.email}" ></input><span>— Enter email</span></div>
<div><input class="pretty-input ${hasErrors(bean:user,field:'password','input-error')}" type="password" name="password"></input><span>— Choose a password</span></div>
<div><input class="pretty-input ${hasErrors(bean:user,field:'password2','input-error')}" type="password" name="password2"></input><span>— Repeat the password</span></div>
如果我删除密码的自定义验证,我的代码可以工作,因为密码 2 的值始终为空。我为什么在所有其他字段都有效但密码 2 无效时会发生这种情况。