A validation rule is a constraint that determines whether submitted data satisfies a required condition. In a Spring MVC form, rules prevent empty fields, invalid formats, and incomplete domain objects from being processed. section 2.3
Apply validation rules by:
- Adding the Spring Validation starter to the build. section 2.3
- Declaring constraint annotations on domain-object properties instead of scattering if/then checks through controller methods. section 2.3 section 2.3.1
- Activating validation in controller methods and displaying field errors in the form view. section 2.3 section 2.3.3
Taco order validation
A Taco requires a non-null name of at least five characters and at least one ingredient. A TacoOrder requires nonblank delivery fields; its credit-card number must pass the Luhn check, expiration must match MM/YY, and CVV must contain three digits. 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;
}
View the complete Taco domain class with @NotNull and @Size constraints, including custom validation messages. section 2.3.1
Listing 2.15 Displaying validation errors
<label for="ccNumber">Credit Card #: </label>
<input type="text" th:field="*{ccNumber}"/>
<span class="validationError"
th:if="${#fields.hasErrors('ccNumber')}"
th:errors="*{ccNumber}">CC Num Error</span>
See how a Thymeleaf field displays a validation message only when the ccNumber property has errors. section 2.3.3




