表单验证 Play 框架 2.0

7
我正在遵循http://www.playframework.org/documentation/2.0/JavaForms上的教程。
我已经创建了一个名为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: No value]]。
因此,它从未检查/到达。
if(loginForm.hasErrors()) 

有人知道这是为什么吗?如果我将值设置为示例中的值:
Map<String,String> anyData = new HashMap();
anyData.put("email", "bob@gmail.com");
anyData.put("password", "secret");

一切都正常,我使用正确的值检索到了LoginForm对象。 我应该捕获异常吗?Play框架不应该处理并设置loginForm.hasErrors = true吗?

感谢任何帮助!


我明白了,但是当我使用loginForm.bindFromRequest().get()时,对于真实的帖子也是一样的,它会绑定来自请求的数据。如果用户没有在表单字段中输入任何数据,该如何验证?而不必编写自己的验证方法? - John Rodrick
但是你说真正的帖子有效,其中在你的映射中没有空值。 - Dan W
抱歉,真正的帖子也没有起作用。输入字段为空。 - John Rodrick
那么填写了电子邮件和密码的帖子没有起作用?你在帖子中说它应该像预期的那样工作。 - Dan W
是的,带有填充字段的真/假帖子有效。然后必需的注释不会产生影响。但如果电子邮件字段为空(它具有@Required注释),则会抛出异常。loginForm.hasErrors() 不应该为true吗?而不是抛出异常? - John Rodrick
显示剩余4条评论
2个回答

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 

0

1
问题已被关闭,因为它是无效的 - 这是预期的行为。 - Michal Bernhard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接