A validation rule is a constraint that determines whether submitted data satisfies a required condition. In a web form, rules can reject missing or incorrectly formatted values before the application accepts them. section 2.3
Spring supports declaring rules with the JavaBean Validation API instead of filling controller methods with repetitive field-by-field checks. Add the Spring Validation starter, annotate the domain-object properties, trigger validation in controller methods, and display any errors in the form. section 2.3
A taco-order form can use rules such as:
- Require a taco name of at least five characters and at least one selected ingredient. section 2.3.1
- Require delivery name and address fields, and check payment values for an acceptable card number, expiration format, and CVV length. 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;
}
See the Taco class with property-level annotations for required values and minimum lengths. section 2.3.1
Rules can check format without confirming real-world validity: the card-number check can catch mistakes or deliberately bad data, but does not establish that the number belongs to an account or can be charged. Forms can display field-specific messages when validation fails. section 2.3.1 section 2.3.3







