I have a bean for which I want to do a conditional check. For this purpose, I defined DefaultGroupSequenceProvider<MyObject> , which returns a list of groups to check.
Now, when checking an object that violates restrictions in more than one group in the sequence, only the first group with failures returns the result. I would like to receive an error in all violations, and not just in the first group with errors.
I think that this does not need a sample code, but if I am mistaken, I will be happy to provide it.
I followed this http://kh-yiu.blogspot.com/2014/04/conditional-bean-validation-using.html when creating the sequence. We use Spring, if that matters.
Just a note, this works, as it is not possible for an invalid bean to be declared valid. But if the user has some input that violates 3 restrictions, and I return 2 failures, the user will receive another failure in the last field, as soon as the first ones are fixed. Not quite clear user.
Example:
Bean
@GroupSequenceProvider(BeanSequenceProvider.class) public class MyBean { @NotEmpty private String name; @NotNull private MyType type; @NotEmpty(groups = Special.class) private String lastName;
Type of listing
public enum MyType { FIRST, SECOND }
Provider
public class BeanSequenceProvider implements DefaultGroupSequenceProvider<MyBean> { @Override public List<Class<?>> getValidationGroups(final MyBean object) { final List<Class<?>> classes = new ArrayList<>(); classes.add(MyBean.class); if (object != null && object.getType() == MyType.SECOND) { classes.add(Special.class); } return classes; }
Group Annotations
public interface Special { }
Testing class
public class MyBeanTest { private static Validator validator; private MyBean objectUnderTest; @BeforeClass public static void setUpOnce() throws Exception { final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); validator = validatorFactory.getValidator(); } @Before public void setUp() throws Exception { objectUnderTest = new MyBean(); objectUnderTest.setName("Simen"); objectUnderTest.setType(MyType.FIRST); objectUnderTest.setLastName("Woop"); } @Test public void testValid() throws Exception { assertThat(validator.validate(objectUnderTest), is(empty())); } @Test public void testMissingName() throws Exception { objectUnderTest.setName(null); assertThat(validator.validate(objectUnderTest), hasSize(1)); } @Test public void testMissingLastName() throws Exception { objectUnderTest.setLastName(null); assertThat(validator.validate(objectUnderTest), is(empty())); objectUnderTest.setType(MyType.SECOND); assertThat(validator.validate(objectUnderTest), hasSize(1)); objectUnderTest.setName(null); assertThat(validator.validate(objectUnderTest), hasSize(2)); }
This last statement fails because there is one violation, not 2. Because the restriction of the restriction in the default group, the Special group is not violated.