按逻辑顺序执行JSR-303验证 [英] Doing JSR-303 validation in logical order

查看:83
本文介绍了按逻辑顺序执行JSR-303验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的域模型类验证约束中有以下字段:

I have such field in my domain model class validation constraints:

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

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

When this field is empty ("") or null, validator produces both "cannot be empty" and "size must be between..." error messages. I understand it, but when I show this validation error to the client, it seems quite odd (because when something is null / empty it cannot fulfill size requirement, it's not a logical).

有什么方法可以告诉Spring以正确的顺序进行验证吗?如果不是@NotEmpty,则不要检查@Size,并且在满足@NotEmpty的情况下检查@Size.

Is there some way how to tell Spring to do validation in proper order? If is not @NotEmpty then do not check @Size, and when @NotEmpty is fulfilled check @Size.

推荐答案

根据

默认情况下,约束的评估没有特定的顺序,并且这 无论它们属于哪个组.在某些情况下, 但是,控制约束的顺序很有用 评估.为了执行这样的命令,可以定义一个新的命令 界面并使用@GroupSequence对其进行注释,以定义顺序 必须验证哪些组.

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.

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

At first, create two interface FirstOrder.class and SecondOrder.class and then define a group sequence inside OrderedChecks.java using @GroupSequence annotation.

public interface FirstOrder {
}

public interface SecondOrder {
}

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

最后,在您的bean约束注释中添加组.

Finally, add groups in your bean constraints annotations.

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

这篇关于按逻辑顺序执行JSR-303验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆