With @Valid
we can parse the request body and validate it with annotations like @NotEmpty
, @Size(min = 5)
. Is there a way to have multiples ways to validate the body? For example, on some endpoints, I would like to ignore some validators (@NotNull
in my case).
My guess was to create a custom annotation like @ValidUnlessNull
, but how can I implement its resolver without having to do the job of @RequestBody
(I tried to implement a Filter
and a HandlerMethodArgumentResolver
)?
To retrieve the body of the POST request sent to the handler, we'll use the @RequestBody annotation, and assign its value to a String. This takes the body of the request and neatly packs it into our fullName String. We've then returned this name back, with a greeting message.
You can define custom validation groups and select any group with @Validated
annotation.
1) Define empty interface, that will be used as validation group identifier:
public interface FirstValidateGroup{}
2) Bind validation annotation to specified interface (group):
public class Person{
@NotBlank(groups = {FirstValidateGroup.class})
private String firstName;
@NotBlank
private String lastName;
//... getters and setters
}
Note, that you can bind multiple groups for one property.
3) Select group of validation with @Validated
annotation:
public ResponseEntity<Person> add(@Validated({FirstValidateGroup.class})
@RequestBody Person person){
...
}
Now, only firstName
property will be validated. You can specify multiple groups in @Validated
annotation.
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