同一属性上的不同 Hibernate 验证注释

发布于 2024-09-28 00:11:55 字数 271 浏览 3 评论 0原文

我在 bean 中的属性上使用两个验证注释:

@NotEmpty(message = "{name.required}")
@Pattern(regex = "^([A-Za-z0-9]{2,}(\\-[a-zA-Z0-9])?)$", message = "{invalid.name}")
private String name;

如果我将名称留空,则会收到两个错误,但我只想要第一个错误消息 (如果第一个条件发生,则显示其错误消息,然后跳过第二个条件)。

I am using two validation annotations on a property in the bean:

@NotEmpty(message = "{name.required}")
@Pattern(regex = "^([A-Za-z0-9]{2,}(\\-[a-zA-Z0-9])?)$", message = "{invalid.name}")
private String name;

If i left the name empty, I got the two errors but I want only the first error message
(if the first condition occurs show its error message then skip the second condition).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

温柔少女心 2024-10-05 00:11:55

如果第一个条件发生,则显示其错误消息,然后跳过第二个条件

这可以通过创建复合约束并使用 @ReportAsSingleViolation 元约束对其进行注释来完成。

UserName.java

@ReportAsSingleViolation
@NotEmpty
@Pattern(regexp="^([A-Za-z0-9]{2,}(\\-[a-zA-Z0-9])?)$")
@Constraint(validatedBy = {})
public @interface UserName {
    String message() default "invalid userName!";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

参考

if the first condition occurs show its error message then skip the second condition

This can be done by creating Composite Constraint and annotating it with @ReportAsSingleViolation meta constraint.

UserName.java

@ReportAsSingleViolation
@NotEmpty
@Pattern(regexp="^([A-Za-z0-9]{2,}(\\-[a-zA-Z0-9])?)$")
@Constraint(validatedBy = {})
public @interface UserName {
    String message() default "invalid userName!";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Reference 3.2. Constraint composition

来世叙缘 2024-10-05 00:11:55

接受的答案并不按您的预期工作。仅当您想要列出 ENTIRE 组合链中的 ALL 错误时,确定约束组合才是好的。如果您想提前退出第一个验证错误,则它不起作用。

@ReportAsSingleViolation 的文档表示忽略每个单独的组合约束的错误报告

使用accept示例

@ReportAsSingleViolation
@NotEmpty
@Pattern(regexp="^([A-Za-z0-9]{2,}(\\-[a-zA-Z0-9])?)$")
@Constraint(validatedBy = {})
public @interface UserName {
    String message() default "invalid userName!";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

这意味着您将收到UserName注释的默认消息错误,即“无效的userName!”即使 @NotEmpty 首先失败......

我必须说我对 java bean 验证实现者的设计如此糟糕感到非常震惊。如果您返回完全不相关的消息,那么组合验证绝对没有意义。它应该首先失败并返回实际失败的验证的相应错误!无论如何,如果没有大量丑陋的黑客攻击,就没有办法做到这一点。如此简单的验证任务变成了一场噩梦。 0_o

我的解决方案是不要编写验证,只需创建 1 个验证并自行实现。它不干燥,但至少很简单。

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PasswordValidator.class)
public @interface Password {
    String message() default "{com.example.Password.message}";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}



public class PasswordValidator implements ConstraintValidator<Password, String> {
    private Pattern twoDigitsPattern;

    public void initialize(Password constraint) {
        twoDigitsPattern = Pattern.compile("(.*[\\d]){2}");
    }

    public boolean isValid(String password, ConstraintValidatorContext context) {
        context.disableDefaultConstraintViolation();

        if (password == null) {
            context.buildConstraintViolationWithTemplate("{javax.validation.constraints.NotNull.message}")
                    .addConstraintViolation();
            return false;
        }

        if (password.length() < 5 || password.length() > 10) {
            context.buildConstraintViolationWithTemplate("must be between 5 to 10 characters")
                    .addConstraintViolation();
            return false;
        }

        if (!twoDigitsPattern.matcher(password).matches()) {
            context.buildConstraintViolationWithTemplate("must contain 2 digits between [0-9]").addConstraintViolation();
            return false;
        }

        return true;
    }

}

The accepted answer doesn't work as you expect. Sure constraint composition is good only if you want to list ALL the errors in the ENTIRE composition chain. It doesn't work if you want to early exit from the first validation error.

The docs for @ReportAsSingleViolation say The error reports of each individual composing constraint are ignored.

Using the accept example

@ReportAsSingleViolation
@NotEmpty
@Pattern(regexp="^([A-Za-z0-9]{2,}(\\-[a-zA-Z0-9])?)$")
@Constraint(validatedBy = {})
public @interface UserName {
    String message() default "invalid userName!";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

This means you will get the default message error of the UserName annotation which is "invalid userName!" even if @NotEmpty fails first....

I must say I am quite shocked at how poor this design is by the java bean validation implementors. It makes absolutely no sense to have composed validations if you return a completely irrelevant message. It should fail first AND return the corresponding error for the validation that actually failed!. Anyway there is no way to do this without massive ugly hacks. Such a simple validation task turns into a nightmare. 0_o

My work around solution is don't compose validations, just create 1 validation and implement it all yourself. Its not DRY but its simple at least.

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PasswordValidator.class)
public @interface Password {
    String message() default "{com.example.Password.message}";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}



public class PasswordValidator implements ConstraintValidator<Password, String> {
    private Pattern twoDigitsPattern;

    public void initialize(Password constraint) {
        twoDigitsPattern = Pattern.compile("(.*[\\d]){2}");
    }

    public boolean isValid(String password, ConstraintValidatorContext context) {
        context.disableDefaultConstraintViolation();

        if (password == null) {
            context.buildConstraintViolationWithTemplate("{javax.validation.constraints.NotNull.message}")
                    .addConstraintViolation();
            return false;
        }

        if (password.length() < 5 || password.length() > 10) {
            context.buildConstraintViolationWithTemplate("must be between 5 to 10 characters")
                    .addConstraintViolation();
            return false;
        }

        if (!twoDigitsPattern.matcher(password).matches()) {
            context.buildConstraintViolationWithTemplate("must contain 2 digits between [0-9]").addConstraintViolation();
            return false;
        }

        return true;
    }

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文