When the PathVariable 'name' doesn't pass validation a javax.validation.ConstraintViolationException is thrown. Is there a way to retrieve the parameter name in the thrown javax.validation.ConstraintViolationException?
@RestController @Validated public class HelloController { @RequestMapping("/hi/{name}") public String sayHi(@Size(max = 10, min = 3, message = "name should have between 3 and 10 characters") @PathVariable("name") String name) { return "Hi " + name; }
javax. validation. ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'.
The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph. However, this creates issues for scenarios needing only partial validation. On the other hand, we can use @Validated for group validation, including the above partial validation.
@NotNull validates that the annotated property value is not null. @AssertTrue validates that the annotated property value is true. @Size validates that the annotated property value has a size between the attributes min and max; can be applied to String, Collection, Map, and array properties.
@Validated annotation is a class-level annotation that we can use to tell Spring to validate parameters that are passed into a method of the annotated class. @Valid annotation on method parameters and fields to tell Spring that we want a method parameter or field to be validated.
If you inspect the return value of getPropertyPath()
, you'll find it'a Iterable<Node>
and the last element of the iterator is the field name. The following code works for me:
// I only need the first violation ConstraintViolation<?> violation = ex.getConstraintViolations().iterator().next(); // get the last node of the violation String field = null; for (Node node : violation.getPropertyPath()) { field = node.getName(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With