What is validation?

  • User input may be different from the requirements from the server
  • In order to prevent any invalid data from being sent to the server or DB, we need to validate the data

 

Example

1. Add dependency

  • Add Gradle dependency
implementation 'org.springframework.boot:spring-boot-starter-validation:3.1.3'

2. Add validation annotations in dto

  • We need to add annotations to the fields that we want to validate
// UserDto.java

public class UserDto {
    private Long id;
    @NotEmpty
    @Email
    private String email;
    @NotEmpty(message = "First Name should not be null or empty")
    private String firstName;
    @NotEmpty
    private String lastName;
}
  • Below is a list of common annotations for validation
Annotation Condition
@NotNull Should not be null
@Null Should be null
@NotEmpty Should not be null or empty
@Max(n) Should be less than or equal to n
@AssertTrue Should be true
@Future Should be a date in the future (based on current date)
@Past Should be a date in the past

3. Enable validation by @Valid annotation in REST APIs

  • In the REST API function that we want to validate the request body, we use @Valid annotation
// UserController.java

@PostMapping
public ResponseEntity<UserDto> createUser(@Valid @RequestBody UserDto userDto) {
    UserDto savedUserDto = userService.createUser(userDto);
    return new ResponseEntity<>(savedUserDto, HttpStatus.OK);
}
  • Then we can see that a validation error response is thrown.

4. Customise validation error response

  • It would be better to have a custom exception for the validation error. 
  • We can use 'handleMethodArgumentNotValid' function from ResponseEntityExceptionHandler.
  • Below, we get a list of validation errors and return it as a response entity.
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
	...
    
    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(
            MethodArgumentNotValidException ex, 
            HttpHeaders headers, 
            HttpStatusCode status, 
            WebRequest request) 
    {
        Map<String, String> errors = new HashMap<>();
        List<ObjectError> errorList = ex.getBindingResult().getAllErrors();
        errorList.forEach(e -> {
            errors.put(((FieldError) e).getField(), e.getDefaultMessage());
        });

        return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
    }
}

The response shown when firstName is empty and email is not well formatted

  • We can customize the message we want to show for the validation error
  • We use the 'message' field inside each annotation
@NotEmpty(message = "First Name should not be null or empty")
private String firstName;

message for invalid firstName has changed

'Spring' 카테고리의 다른 글

Spring Data JPA - Custom Query Methods  (0) 2023.10.30
Spring Boot Exception Handling  (0) 2023.09.14
DTO (Data Transfer Object)  (0) 2023.09.14
Spring Data JPA Repository  (0) 2023.09.01
Spring Data JPA Entity  (0) 2023.09.01

+ Recent posts