我无法从我的视图中访问 ValidationError 消息。我设法获得的唯一输出是:
[ValidationError(username,Too short, sorry ;),[6])]
[ValidationError(password,Confirmation password doesn't match,[])]
我只想输出错误消息:“太短,抱歉;)”和“确认密码不匹配”。
我找到的解决方法是从表单中调用特定字段,然后访问错误消息:
@form("password").error.map(_.message).getOrElse("")
谢谢,
我的观点 register.scala.html :
@if(form.hasErrors) {
<div class="form-group">
<div class="alert alert-danger col-lg-6 text-center">
@for((key, vamlue) <- form.errors){
@value<br />
}
</div>
</div>
}
我的控制器:
public static Result registerSubmit(){
Form<User> registerForm = form(User.class).bindFromRequest();
String passwordConfirmation = registerForm.field("passwordConfirmation").value();
if(!registerForm.field("password").valueOr("").equals(passwordConfirmation)){
ValidationError e = new ValidationError("password", "Confirmation password doesn't match");
registerForm.reject(e);
}
if (registerForm.hasErrors()){
// Handle Error
return badRequest(register.render(registerForm));
} else {
// Check if all data are fine
// TODO : Redirect to Login Page
return ok(register.render(registerForm));
}
}
最后是模型 User.java :
@Required
@MinLength(6)
String username;
@Required
@Email
String email;
@Required
@MinLength(6)
String password;