本文介绍了在验证功能中添加全局错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个登录表格:

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

我需要验证用户是否存在或已被验证.所以我的验证功能是:

And I need to validate if user exist or is validated. So my validate function is:

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

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

But how to make these errors global?

推荐答案

好,我找到了解决方案.我必须将ValidationError第一个参数的构造方法传递为空字符串.因此整个代码如下:

Ok I found out solution. I have to pass to concstuctor of ValidationError first argument as empty string. So whole code looks like:

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

这篇关于在验证功能中添加全局错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:47