我想在项目的注册页面添加密码确认。但是我的某个领域的价值存在问题。所有字段都可以,但是password2字段,它是确认密码,是用户域类的瞬态字段。这是我的域名,控制器和查看代码
域类:
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>
如果我删除密码的自定义验证,我的代码有效,因为password2的值始终为null。我为什么会在所有其他字段工作但密码2不工作时发生这种情况。
答案 0 :(得分:3)
默认情况下,Trasients字段不是可绑定的,因此您无法传递params来填充它。
你可以这样做:
static constraints = {
... your code here
password2 bindable: true
}
但我建议您使用命令对象来验证该条件,它很聪明。