JSR-303 how to ignore validation on specific fields in a bean some of the time

白昼怎懂夜的黑 提交于 2019-12-06 08:55:42

问题


I am validating a large bean. It is based of a dynamic form page. Some fields that are being validated are not visible on the form and hence empty or null. But I don't want the invisible fields to be validated. Sometimes they are visible and I want them to be validated, sometimes they are not visible and I don't want them to be validated. I first took the approach of stripping these fields from the serialized form before submitting. But it still validates the missing fields because they exist in the bean with validation tags. What is the right way to do what I am trying to do?


回答1:


One possible approach is using validation groups. You define different validation rules for different groups. Afterwards you can call the validator just for one of these groups or for a set of groups.

public class TestBean {

    @NotNull(groups= {Group1.class})
    @Size.List({
        @Size(min=1, groups= {Group1.class}),
        @Size(min=0, groups= {Group2.class})
    })
    private String test;
}

public interface Group1 { }
public interface Group2 { }

then you can call the validator for one or more of these groups

Validator validator = ....;
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(objectToValidate, Group1.class);

For more information about validating groups see here.



来源:https://stackoverflow.com/questions/14480489/jsr-303-how-to-ignore-validation-on-specific-fields-in-a-bean-some-of-the-time

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