liveBook · Manning

JavaBean Validation API

As explained in Spring in Action, Sixth Edition

The Java standard for declaring and evaluating constraints on Java object properties and method parameters, originally specified as JSR 303.

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

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains dependency setup, property annotations, controller integration, messages, and view errors, but defers regular-expression details.
Examples
Uses Taco and TacoOrder fields, delivery addresses, credit-card checks, expiration patterns, CVV digits, and ingredient counts.
What you can do after
Apply it via Spring MVC to declare constraints, trigger validation, and show submitted-form errors.
How it connects
Connects validation constraints with Spring MVC, Hibernate Validator, domain objects, controllers, and form views.

Also explained in

Compare how 2 books explain JavaBean Validation API →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.