Objective

Implement presentation logic (P.L.) validations in a Spring Boot backend and handle exceptions centrally to provide consistent and user-friendly error responses to REST clients.

Steps for Adding Validations

1.1 Add Validation Dependency

Ensure the Spring Boot validation starter dependency is included in pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

1.2 Define Validation Rules

Add validation annotations to properties of POJOs (Entity or DTO) to enforce rules. These annotations are imported from javax.validation.constraints and org.hibernate.validator.constraints.

Example Validation Rules:

Example DTO:

public class UserDTO {
    @NotBlank(message = "First name cannot be blank")
    @Size(min = 4, max = 20, message = "First name must be between 4 and 20 characters")
    private String firstName;

    @NotBlank(message = "Last name cannot be blank")
    private String lastName;

    @Email(message = "Invalid email format")
    @NotBlank(message = "Email cannot be blank")
    private String email;

    @Pattern(regexp = "(?=.*\\\\d)(?=.*[a-z])(?=.*[#@$*]).{5,20}",
             message = "Password must be 5-20 characters with alphanumeric and special characters (#@$*)")
    private String password;

    @Range(min = 500, max = 5000, message = "Registration amount must be between 500 and 5000")
    private double regAmount;

    @Future(message = "Registration date must be in the future")
    private LocalDate regDate;
}

Testing: Use a tool like Postman to test the API with invalid inputs and verify validation responses.

Note: These annotations (@NotBlank, @NotNull, @Email, @Pattern, @Future, @Range, @Min, @Max) are also used in Spring MVC standalone applications for presentation logic validations.

1.3 Validate RequestBody