JSR-303 validation groups define a default group : <p>I have a bean that has a lot of fields annotated with JSR-303 validation annotations. There is a new requirement now that one of the fields is mandatory, but only in certain conditions.</p>

<p>I looked around and have found what I needed, validation groups.</p>

<p>This is what I have now:</p>

<pre><code>public interface ValidatedOnCreationOnly {
}

@NotNull(groups = ValidatedOnCreationOnly.class)
private String employerId;
@Length(max = 255)
@NotNull
private String firstName;
@Length(max = 255)
@NotNull
private String lastName;
</code></pre>

<p>However, when I run this validation in a unit test:</p>

<pre><code>@Test
public void testEmployerIdCanOnlyBeSetWhenCreating() {
    EmployeeDTO dto = new EmployeeDTO();

    ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
    Set&lt;ConstraintViolation&lt;EmployeeDTO&gt;&gt; violations = vf.getValidator().validate(dto, EmployeeDTO.ValidatedOnCreationOnly.class);

    assertEquals(violations.size(), 3);
}
</code></pre>

<p>It turns out that all of the non-group annotated validations are ignored and I get only 1 violation.</p>

<p>I can understand this behaviour but I would like to know if there is a way I can make the group include all non-annotated parameters as well. If not I'd have to do something like this:</p>

<pre><code>public interface AlwaysValidated {
}

public interface ValidatedOnCreationOnly extends AlwaysValidated {
}

@NotNull(groups = ValidatedOnCreationOnly.class)
private String employerId;
@Length(max = 255, groups = AlwaysValidated.class)
@NotNull(groups = AlwaysValidated.class)
private String firstName;
@Length(max = 255, groups = AlwaysValidated.class)
@NotNull(groups = AlwaysValidated.class)
private String lastName;
</code></pre>

<p>The real class I'm working with has a lot more fields (about 20), so this method turns what was a clear way of indicating the validations into a big mess.</p>

<p>Can anyone tell me if there is a better way? Maybe something like:</p>

<pre><code>vf.getValidator().validate(dto, EmployeeDTO.ValidatedOnCreationOnly.class, NonGroupSpecific.class);
</code></pre>

<p>I'm using this in a spring project so if spring has another way I'll be glad to know.</p>
