I have a POJO with some fields annotated with @NotEmpty:
public class SampleFormInputDTO {
@NotEmpty
private String textarea;
private int myInt = 0;
@NotEmpty
private String myText = "somevalue";
public String getTextarea() {
return textarea;
}
public void setTextarea(String textarea) {
this.textarea = textarea;
}
}
The intention is that the fields will be checked to ensure they contain a value i.e not null and not empty.
If I create an instance of SampleFormInputDTO using no-args constructor, the field textarea will be null initially so should and does fail validation as expected.
SampleFormInputDTO sampleFormInputDTO = new SampleFormInputDTO();
ValidatorFactory validatorFactory =
Validation.byDefaultProvider()
.configure()
.messageInterpolator(new ParameterMessageInterpolator())
.buildValidatorFactory();
Validator validator = validatorFactory.getValidator(sampleFormInputDTO);
Set<ConstraintViolation<SampleFormInputDTO>> violationSet = validator.validate();
I'm wondering if it is possible to dynamically / programmatically indicate to the validator instance to not validate a specific constraint annotation for a specific field?
Suppose I've determined, as part of handling a REST API invocation that I want the field textarea of type SampleFormInputDTO to allow empty strings dynamically, but only for that specific field. Not affecting any constraint annotations that may be present on other fields in the same POJO.
Is this possible?
You might want to take a look at the validation groups.
Then you can control which constraints are included in validation and which are not, for example:
will only check
myTextproperty, but then something like:will validate both.