简体   繁体   中英

How to Display form validation errors

I wonder how to display the error message from my model in the function validate() that returns "invalid username or password" when the submit is not "valid"

index.scala.html

@(myForm: Form[models.profile.MUser])

@import helper._
@import helper.twitterBootstrap._

@main("welcome") {

  <h1>Login with your account</h1>

@helper.form(action = routes.Application.loginAccount()) {

    @helper.inputText(myForm("username"),'_showConstraints -> false)
    @helper.inputPassword(myForm("password"),'_showConstraints -> false)

    <input type="submit" value="Login">
}}

Application.java

public static Result loginAccount() {
        Form<MUser> filledform = loginForm.bindFromRequest();
        if (filledform.hasErrors()) {
            Logger.debug("unsuccessfull loggin");
              return badRequest(index.render(filledform));
        }
        MUser user = filledform.get();
        SessionCache.setCache(SessionCache.Constants.LOGGED_IN_USER,
                UserController.findUserByUserName(user.username));
        return redirect("/home");

    }

MUser.java package models.profile;

import controllers.services.UserController;
import models.entities.UserDTO;
import play.data.validation.Constraints.*;
import scala.Serializable;

/**
 * @author fbranchetti
 * 
 */
public class MUser implements Serializable{

    @Required
    public String username;
    @Required
    public String password;


    public String validate() {
        if (authenticate(username, password)) {
            return "Invalid username or password";
        }
        return null;
    }


    private boolean authenticate(String username, String password) {
        UserDTO fUser = new UserDTO();
        fUser.setPassword(password);
        fUser.setUsername(username);

        return !UserController.logginUser(fUser);
    }

}

You can store the result of the authenticate in a flash variable. And in the view, you can check for the existence of the variable and display it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM