Doing JSR-303 validation in logical order

自作多情 提交于 2019-12-10 10:45:12

问题


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;

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).

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.


回答1:


According to 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.

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

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;



回答2:


The following example is taken from the JSR-303 docs

public class Address {
    @NotEmpty(groups = Minimal.class)
    @Size(max=50, groups=FirstStep.class)
    private String street1;

    @NotEmpty(groups=SecondStep.class)
    private String city;

    @NotEmpty(groups = {Minimal.class, SecondStep.class})
    private String zipCode;
    ...

    public interface FirstStep {}

    public interface SecondStep {}

    @GroupSequence({Firststep.class, SecondStep.class})
    public interface Total {}
}

and calling the validator like this

validator.validate(address, Minimal.class, Total.class);


来源:https://stackoverflow.com/questions/42447159/doing-jsr-303-validation-in-logical-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!