I wonder why the accepted answer suggests groups? If we keep in mind what OP asks "I need to exclude some fields from validation (only for some cases)." The answer is "Not possible" You can not exclude only in some cases. Actually what you have to do is include everywhere except were not needed. If I have an object with many fields or an object that is composed of other objects and the nesting is deep:
public class Person {
@NotNull
private String firstName;
@NotNull
private String lastName;
@Valid
@NotNull
private Address address;//deep object
<...many more fields...>
}
And the object is used in 100 places (speaking figuratively). And i want to allow field lastName
to be null
in just one place (speaking figuratively). Using groups requires to make changes on all fields and on all nested object fields and also in all places where this object Person is used.
I would rather only mark the field in question, and make changes only in that one particular place. Not possible. Prove me wrong :)