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

I am checking a large bean. It is based on a dynamic form page. Some of the fields that are validated are not visible on the form and are therefore empty or null. But I don't want invisible fields to be checked. Sometimes they are visible and I want to be checked, sometimes they are not visible and I don't want to be checked. I first took the approach of removing 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 correct way to do what I am trying to do?

+3


source to share


1 answer


One possible approach is to use review teams. You define different validation rules for different groups. Subsequently, you can call the validator for only 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 on checking groups see here .

+3


source







All Articles