【问题标题】:How to Display form validation errors如何显示表单验证错误
【发布时间】:2012-08-24 02:49:54
【问题描述】:

我想知道如何在提交不是“有效”时返回“无效用户名或密码”的函数 validate() 中显示来自我的模型的错误消息

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

}

【问题讨论】:

    标签: html forms validation scala playframework-2.0


    【解决方案1】:

    您可以将身份验证的结果存储在 flash 变量中。 并且在视图中,可以检查变量是否存在并显示出来。

    【讨论】:

      猜你喜欢
      • 2018-01-02
      • 2018-04-19
      • 2014-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多