2012-04-02 45 views
7

我在下面http://www.playframework.org/documentation/2.0/JavaForms表單驗證發揮框架2.0

我從例子中創建的類LoginForm.java(而不是User.class的教程。不是爲堅持類,只是一種形式值持有者)

package domain; 

import static play.data.validation.Constraints.*; 

public class LoginForm { 

     @Required 
     public String email; 
     public String password; 

} 

而且在我的控制器怎麼辦?(作爲例子),但我設置的值爲空字符串嘗試@Required註解。

Form<LoginForm> loginForm = form(LoginForm.class); 
Map<String,String> anyData = new HashMap(); 
anyData.put("email", ""); 
anyData.put("password", ""); 

//Faking a post 
LoginForm postedLoginForm = loginForm.bind(anyData).get(); 

if(loginForm.hasErrors()) { 
    //Just for this test task, should have another error handling.. 
    return ok("@Required annotation kicked in.."); 
} else { 
    return ok("Got form values, email: " + postedLoginForm.email + " password: " + postedLoginForm.password); 
} 

但在:

LoginForm postedLoginForm = loginForm.bind(anyData).get(); 

我得到一個執行異常[IllegalStateException異常:無值]

所以它永遠不會檢查/談到

if(loginForm.hasErrors()) 

有誰知道這是爲什麼?如果我設置的值爲例:

Map<String,String> anyData = new HashMap(); 
anyData.put("email", "[email protected]"); 
anyData.put("password", "secret"); 

一切正常,我檢索LoginForm對象與正確的值。 我應該趕上例外嗎?不應該玩的照顧,並設置loginForm.hasErrors = true?

感謝您的幫助!

+0

看起來IllegalStateException來自'bind'。也許這種方法不允許你在地圖沒有數據時「綁定」或「獲取」。 – 2012-04-02 20:56:30

+0

我看到了,但是當我使用loginForm.bindFromRequest()。get()綁定請求中的數據時,這同樣適用於真正的帖子。如果用戶沒有在表單字段中輸入任何數據,如何驗證?無需編寫自己的驗證方法? – 2012-04-02 21:01:17

+0

但是你說過真正的貼子是在你的地圖中沒有空值的作品。 – 2012-04-02 21:03:03

回答

25

這是預期的行爲。

請注意,您必須在窗體上使用.get()之後檢查錯誤。

LoginForm preLoginForm = loginForm.bind(anyData); 

if(loginForm.hasErrors()) { 
    //Just for this test task, should have another error handling.. 
    return ok("@Required annotation kicked in.."); 
} 
LoginForm postedLoginForm = preLoginForm.get(); 
// ... Now use postedLoginForm