Wessel van der Linden
Wessel van der Linden

Reputation: 2622

bindFromRequest validation null

I am new to the Java Play Framework and I'm trying to get the authentication to work. So I am following this tutorial: https://www.playframework.com/documentation/2.1.0/JavaGuide4

Here is my code:

public static Result authenticate()
{
    Form<Login> loginForm = form(Login.class).bindFromRequest();

    return ok(loginForm.toString());

}


public static class Login
{
    public String email;
    public String password;

    public String validate()
    {
        return "VALIDATE "+email+password;
    }
}

In the method autheticate() I can see the submitted values of the form, but the method validate() in the Login class does not see them (the variables are always null).. The output of loginForm.toString() contains:

Form(of=class controllers.Application$Login, data={email=asdf@asdf, password=asdf}, value=None, errors={=[ValidationError(,[VALIDATE nullnull],[])]})

As you can see, the data is received.. But in the validate method the data suddenly is equal to null. So how do I fix this?

Upvotes: 0

Views: 390

Answers (2)

Mateusz
Mateusz

Reputation: 426

Method validate in your model should return null if you think that validation has passed, otherwise you should return error message text. Then you need to check form if it contains error by "hasGlobalError" method. globalError is filled when validate() method returns String instead of null. But in your case you should use some model field annotations - https://www.playframework.com/documentation/2.3.x/api/java/play/data/validation/Constraints.html.

If you want to check if form fails on those - then you use "hasErrors" method.

public static class Login {
@Constraints.Email
public String email;
@Constraints.MinLength(value = 6)
public String password;
}

Such model will check if provided emails is really email and if password is longer or equal 6 characters.

ps. Do not use toString on template, you should use render()

Upvotes: 0

Neilos
Neilos

Reputation: 2746

You don't mention how you are calling validate() however I think this might do the trick, do something along the lines of:

public static Result authenticate() {
    Form<Login> form = form(Login.class).bindFromRequest();

    // handle errors
    if (!form.hasErrors()) {
        Login login = form.get();
        Logger.debug(login.validate());
    } else {
        // bad request
    }
}

This works for me.

Upvotes: 1

Related Questions