The JavaBean Validation API, also called JSR 303, lets applications declare validation rules on Java object properties instead of filling controller methods with repetitive if/then checks. In Spring MVC, those rules validate submitted forms and can be connected to views that display errors. section 2.3 section 2.6
A Spring MVC validation workflow typically requires:
- Add the Spring Validation starter to the build; Spring Boot 2.3.0 and later require this dependency explicitly. section 2.3
- Declare constraints on the domain object being validated, such as @NotNull, @Size, and @NotBlank. section 2.3 section 2.3.1
- Trigger validation in controller methods and update form views to display validation errors. section 2.3
Validating a taco order
A TacoOrder can require nonblank deliveryName, deliveryStreet, deliveryCity, deliveryState, and deliveryZip values with @NotBlank. It can check ccNumber with Hibernate Validator’s @CreditCardNumber, enforce an MM/YY expiration format with @Pattern, and require exactly three numeric CVV digits with @Digits. Each annotation can provide a user-facing message. section 2.3.1
Listing 2.11 Adding validation to the Taco domain class
package tacos;
import java.util.List;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import lombok.Data;
@Data
public class Taco {
@NotNull
@Size(min=5, message="Name must be at least 5 characters long")
private String name;
@NotNull
@Size(min=1, message="You must choose at least 1 ingredient")
private List<Ingredient> ingredients;
}
Inspect a complete Taco domain class using @NotNull and @Size to require a sufficiently long name and at least one ingredient. section 2.3.1

