1

我有一个登录表单:

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

但是如何使这些错误全局化呢?

4

1 回答 1

2

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

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;
    }
}
于 2013-09-22T11:10:52.573 回答