I have a class with validation annotations on my properties, like this one:
@NotNull(payload = INVALID_CATEGORY_DESCRIPTION.class)
@Size(min = 1, max = 255, payload = INVALID_CATEGORY_DESCRIPTION_LENGHT.class)
private String description;
Then I have a @ControllerAdvice to handle validation exceptions.
@ResponseStatus(BAD_REQUEST)
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> methodArgumentNotValidException(MethodArgumentNotValidException exception) {
When one or more validation annotation fail, the exception handler is triggered as expected.
In order to get the payload property from the annotations, I am iterating over the fields with validation errors, then over the annotations and only then comparing the annotation name with the FieldError code. With the annotation in hands I can access the payload.
I wonder if there is a more elegant way to get the payload or the annotation which triggered the exception, as there is for the message property (exception.getMessage()).
@NotNull validates that the annotated property value is not null. @AssertTrue validates that the annotated property value is true.
The @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. We'll learn more about how to use it in the section about validating path variables and request parameters.
@Email annotation is part of javax. validation. constraints package. Using Just @Email annotation like below @Data.
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.
Assuming your starting point is a ConstraintViolationException
you are getting the set of ConstraintViolation
instances via getConstraintViolations()
.
Each ConstraintViolation
then has a getConstraintDescriptor()
, which gives you metadata about the failing constraints. Once you have the ConstraintDescriptor
you just call getPayload()
.
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