Form validation play framework 2.0

2019-03-27 18:43发布

问题:

I'm following the tutorial at http://www.playframework.org/documentation/2.0/JavaForms

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;

}

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);
}

But at:

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

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");

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?

Thanks for any help!

回答1:

This is expected behavior.

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:

This seems to be a bug with Play 2.0 framework. I was able to replicate the same problem locally.

I opened a ticket https://play.lighthouseapp.com/projects/82401-play-20/tickets/313 in case you want to follow up.