Reputation: 1021
How do you check which field in the bean actually had a violation?
Consider this code:
Set<ConstraintViolation<Contact>> violations = validator.validate(contact);
if(violations.isEmpty()) {
} else {
violations.forEach(violation -> {
// Check which field bean field had a violation
});
}
So you can do something like this:
if(fieldWithError.equals("email") && (error instanceof ShouldBeGmail)) {
doThis();
} else if(fieldWithError.equals("phoneNumber") && (error instanceof ShouldBeWithinCountry)) {
doThat();
}
Upvotes: 0
Views: 124
Reputation: 35282
This should work:
if(violations.isEmpty()) {
} else {
violations.forEach(violation -> {
String fieldName = violation.getPropertyPath().toString();
});
}
Upvotes: 1