Fireburn
Fireburn

Reputation: 1021

Check which bean field had a violation

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

Answers (1)

quarks
quarks

Reputation: 35282

This should work:

if(violations.isEmpty()) {
} else {
  violations.forEach(violation -> {
     String fieldName = violation.getPropertyPath().toString();
  });
}

Upvotes: 1

Related Questions