implementation 'org.springframework.boot:spring-boot-starter-validation:3.2.2'
Без Spring boot нужно добавить только зависимость:
implementation 'org.hibernate:hibernate-validator:8.0.1.Final'
@Valid User user
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(
MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach((error) -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return errors;
}
//пример проверки вложенных свойств
@Valid
@NotNull(groups = AdvanceInfo.class)
private UserAddress useraddress;
//объявление
@NotNull(groups = BasicInfo.class)
private String password;
//указание проверки
@Validated(BasicInfo.class) UserAccount useraccount,
@NotNull(message = "Name is mandatory.")
private String name;
@NotEmpty(message = "Name may not be empty")
@Size(min = 2, max = 32, message = "Name must be between 2 and 32 characters long")
private String name;