spring - 按逻辑顺序进行 JSR-303 验证

标签 spring validation bean-validation

我的域模型类验证约束中有这样的字段:

@Column(nullable = false, name = "name")
    @NotEmpty(groups = {Envelope.Insert.class, Envelope.Update.class})
    @Size(min = 3, max = 32)
    private String name;

当此字段为空 ("") 或 null 时,验证器会生成“不能为空”和“大小必须介于...”错误消息。我理解它,但是当我向客户端显示此验证错误时,这似乎很奇怪(因为当某些内容为空/空时,它无法满足大小要求,这不符合逻辑)。

有什么方法可以告诉 Spring 按正确的顺序进行验证吗?如果不是@NotEmpty,则不检查@Size,当满足@NotEmpty时,检查@Size

最佳答案

根据Hibernate official document:

By default, constraints are evaluated in no particular order and this regardless of which groups they belong to. In some situations, however, it is useful to control the order of the constraints evaluation. In order to implement such an order one would define a new interface and annotate it with @GroupSequence defining the order in which the groups have to be validated.

首先,创建两个接口(interface) FirstOrder.class 和 SecondOrder.class,然后使用 @GroupSequence 注解在 OrderedChecks.java 中定义一个组序列。

public interface FirstOrder {
}

public interface SecondOrder {
}

@GroupSequence({FirstOrder.class, SecondOrder.class})
public interface OrderedChecks {
}

最后,在 Bean 约束注释中添加组。

@Column(nullable = false, name = "name")
@NotEmpty(groups = {FirstOrder.class, Envelope.Insert.class, Envelope.Update.class})
@Size(min = 3, max = 32, groups=SecondOrder.class)
private String name;

关于spring - 按逻辑顺序进行 JSR-303 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42447159/

相关文章:

javascript - 用 Parsley 验证多个字段?

javascript - 使用 JQuery,如何检查字符串是否是字母字符后跟八位数字?

spring - 如何自定义 BigDecimal 的默认消息

java - 如果 Spring 配置文件与指定的配置文件不同,如何使用注释 @Profile 跳过服务类

java - Hibernate SessionFactory 与 EntityManagerFactory

ASP.Net 验证摘要导致页面跳转到顶部

java - 由于@Constraint validatedBy,如何避免层之间的交叉依赖?

java - Spring Boot 请求对象验证

java - 使用 Spring Boot 和 Thymeleaf 发送 HTML 电子邮件

java - Rest Api 调用使用 Spring Oauth2 给出错误 400