表单验证播放框架2.0 [英] Form validation play framework 2.0
问题描述
我正在关注 http://www.playframework.org/documentation/2.0/JavaForms
我创建了一个类LoginForm.java(而不是示例中的User.class。不是用于持久化的类,只是一个表单值持有者)
I've created a class LoginForm.java (Instead of User.class from the example. Not a class for persisting, just a form values holder)
package domain;
import static play.data.validation.Constraints.*;
public class LoginForm {
@Required
public String email;
public String password;
}
在我的控制器中我做(作为示例),但我将值设置为空字符串以尝试@Required注释。
And in my controller i do (as the example), but i set the values to empty Strings to try the @Required annotation.
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:No value]]
I get an Execution exception [[IllegalStateException: No value]]
因此它永远不会检查/来到
So it never checks/comes to
if(loginForm.hasErrors())
有谁知道这是为什么?如果我将值设置为示例:
Does anyone know why this is? If i set the values as the example:
Map<String,String> anyData = new HashMap();
anyData.put("email", "bob@gmail.com");
anyData.put("password", "secret");
一切正常,我使用正确的值检索LoginForm对象。
我应该抓住异常吗?不应该玩,并设置loginForm.hasErrors = true?
Everything works and i retrieve the LoginForm object with the correct values. Am i supposed to catch the Exception? Shouldn't play take care of that and set loginForm.hasErrors = true?
感谢您的帮助!
推荐答案
这是预期的行为。
请注意,您必须使用表格上的.get()检查错误后。
Note that you must use .get() on form After check for errors.
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
这篇关于表单验证播放框架2.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!