2012-08-31 70 views
0

我想將密碼確認添加到我的項目註冊頁面。但是我的某個領域的價值存在問題。所有字段都可以,但密碼2字段,它是確認密碼,並且是用戶域類的臨時字段。這裏是我的域,控制器和視圖代碼Grails表單字段總是爲空

域類:

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沒有

+0

在我看來,我沒有看到密碼確認作爲用戶的財產。這只是一個恰好被用戶使用的表單字段。我認爲你應該比較用戶的密碼和確認字段,如params.password2 == user.password –

回答

3

默認情況下,Trasients字段不是可綁定的,因此您無法通過params來填充它。

你可以這樣做:

static constraints = { 
    ... your code here 
    password2 bindable: true 
} 

但我建議你使用一個命令對象來驗證條件,這是聰明的。

+0

這工作!謝謝你的回答 –