Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get field name when javax.validation.ConstraintViolationException is thrown

Tags:

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; } 
like image 568
Josh Avatar asked Apr 11 '16 17:04

Josh


People also ask

What is javax validation ConstraintViolationException?

javax. validation. ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'.

Is @valid and @validated the same?

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.

What does javax validation constraints NotNull do?

@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.

What does @validated do?

@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.


1 Answers

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(); } 
like image 164
leowang Avatar answered Sep 19 '22 23:09

leowang