Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form validation play framework 2.0

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", "[email protected]");
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!

like image 516
John Rodrick Avatar asked Apr 02 '12 19:04

John Rodrick


1 Answers

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 
like image 120
Petter Kjelkenes Avatar answered Oct 02 '22 17:10

Petter Kjelkenes