在验证功能中添加全局错误

时间:2013-09-22 11:03:54

标签: java forms validation playframework-2.2

我有一个登录表单:

public static class LoginForm {
    @Constraints.Required
    public String email;
    @Constraints.Required
    public String password;
}

我需要验证用户是否存在或是否已经过验证。所以我的验证功能是:

public List<ValidationError> validate() {
    List<ValidationError> errors = new ArrayList<ValidationError>();
    User user = User.findByEmail(email);
    if (user == null || !Hash.checkPassword(password, user.passwordHash)) {
        errors.add(new ValidationError("email", "Invalid email"));
        return errors;
    } else if (!user.validated) {
        errors.add(new ValidationError("email", "Not validated email"));
        return errors;
    }
     return null;
} 

但如何将这些错误全局化?

1 个答案:

答案 0 :(得分:2)

好的,我找到了解决方案。我必须将ValidationError的第一个参数作为空字符串传递给concstuctor。所以整个代码看起来像:

public static class LoginForm {
    @Constraints.Required
    public String email;
    @Constraints.Required
    public String password;

    public List<ValidationError> validate() {
        List<ValidationError> errors = new ArrayList<ValidationError>();
        User user = User.findByEmail(email);
        if (user == null || !Hash.checkPassword(password, user.passwordHash)) {
            errors.add(new ValidationError("", "Invalid email"));
            return errors;
        } else if (!user.validated) {
            errors.add(new ValidationError("", "Not validated email"));
            return errors;
        }
        return null;
    }
}