SpringBoot Validations

Validation is like a quality check for data, Spring Boot provides various mechanisms for validation, including annotations, custom validators, error handling and group validation.

Validation Annotations

In Spring Boot, validation is made easier with annotations that mark fields with specific validation rules. Let’s consider an example of validating a simple registration form for a customer:


                    public class CustomerRequest {

                      @JsonProperty("customerName")
                      @NotBlank(message = "Please provide username")
                      private String customerName;
                  
                      @JsonProperty("customerAge")
                      @NotBlank(message = "Please provide customerAge")
                      private int customerAge;
                  
                      @JsonProperty("customerMobileNumber")
                      @NotBlank(message = "Please provide customerMobileNumber")
                      @Size(min = 10, max = 10, message = "Please provide the valid mobile number")
                      private String customerMobileNumber;
                  
                      @JsonProperty("customerEmailAddress")
                      @NotBlank(message = "Please provide customerEmailAddress")
                      @Email(message = "please provide valid email address")
                      private String customerEmailAddress;
                  
                      @JsonProperty("customerAddress")
                      @NotBlank(message = "Please provide customerAddress")
                      private String customerAddress;
                  }
                  

  1. ❆ @NotNull: Ensures a field is not null.
  2. ❆ @NotBlank: Enforces non-nullity and requires at least one non-whitespace character.
  3. ❆ @NotEmpty: Guarantees that collections or arrays are not empty.
  4. ❆ @Min(value): Checks if a numeric field is greater than or equal to the specified minimum value.
  5. ❆ @Max(value): Checks if a numeric field is less than or equal to the specified maximum value.
  6. ❆ @Size(min, max): Validates if a string or collection size is within a specific range.
  7. ❆ @Pattern(regex): Verifies if a field matches the provided regular expression.
  8. ❆ @Email: Ensures a field contains a valid email address format.
  9. ❆ @Digits(integer, fraction): Validates that a numeric field has a specified number of integer and fraction digits.
  10. ❆ @Past and @Future: Checks that a date or time field is in the past and future respectively.
  11. ❆ @AssertTrue and @AssertFalse: Ensures that a boolean field is true. and false respectively.
  12. ❆ @CreditCardNumber: Validates that a field contains a valid credit card number.
  13. ❆ @Valid: Triggers validation of nested objects or properties.
  14. ❆ @Validated: Specifies validation groups to be applied at the class or method level.
@Valid annotation

When you apply the @Valid annotation to a method parameter, Spring Boot automatically triggers validation for that parameter before the method is invoked. It is placed before the object to indicate that it should be validated. This means that the incoming data for that parameter will be validated against the specified validation rules.


                    @PostMapping("/create")
                    public ResponseEntity<APIResponse> createCustomer(@RequestBody @Valid CustomerRequest request, BindingResult bindingResult) {
                        if (bindingResult.hasErrors()) {
                            return ResponseEntity.ok(APIResponse.builder()
                                    .errorCode(HttpStatus.BAD_GATEWAY.value())
                                    .errorMessage(HttpStatus.BAD_GATEWAY.toString())
                                    .data(bindingResult.getFieldErrors().stream()
                                            .map(fieldError -> fieldError.getDefaultMessage())
                                            .toList())
                                    .build());
                        }
                        return customerService.createCustomer(request);
                    }
                  

If the data fails validation, Spring Boot will automatically generate validation error messages and associate them with the appropriate fields in the input data. These validation errors are typically captured in a BindingResult object, which you can access to analyze and handle validation failures.

Validation on Nested Properties

When dealing with complex objects that have nested properties requiring validation, you can use the @Valid annotation along with validation annotations to ensure that both the top-level object and its nested properties are properly validated.


                    
                    // Customer address annotated with @Valid in CustomerRequest object
                    @JsonProperty("customerAddress")
                    @Valid
                    private CustomerAddress customerAddress;


                    public class CustomerAddress {
                      @JsonProperty("address")
                      @NotBlank(message = "Please provide the customer address")
                      private String address;
                  
                      @JsonProperty("city")
                      private String city;
                  
                      @JsonProperty("state")
                      private String state;
                  
                      @JsonProperty("country")
                      @NotBlank(message = "Please provide the country")
                      private String country;
                  }
                  

Full source code is available in follwong GitHub repository: SpringBoot Form Validations

Testing through postman