问题
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