@RequestBody Validation
- Used with @Valid or @Validated to validate incoming request body (POJO) before method execution.
- If validation fails, throws a
MethodArgumentNotValidExceptionand returns a 400 Bad Request response.
Requirements:
- Add
spring-boot-starter-validationdependency (Hibernate Validator). - Add validation annotations in the model ( @NotNull,@NotEmpty,@Email).
- Use @Valid or @Validated before the @RequestBody parameter.
Example
Model Class :
public class User {
@NotBlank
private String name;
@Email
private String email;
@Min(18)
private int age;
}
In Invalid request:
Response: 400 Bad Request With error details like:
{
"errors": [
"name must not be blank",
"email must be a valid email address",
"age must be greater than or equal to 18"
]
}