Validating Required Fields
Explore how to add and validate required fields in Spring MVC forms by using Jakarta validation annotations like @NotNull, @Size, and @NotEmpty. Understand how to handle user input trimming with the @InitBinder annotation to preprocess form data, ensuring that whitespace inputs are validated correctly. This lesson teaches you to create robust form validation and customization techniques in Spring MVC applications.
We'll cover the following...
A required filed is a mandatory field that must be filled in before the form is submitted. In this lesson, we will add a required field to our form. The add-player-form has a textbox for name that stores data in the lastName field of the Athlete class. We will change this field and split it into first name and last name, with the latter being a required field. The first name can be left blank.
When the user clicks on the "Add player" button on the add-player-form.jsp , the request goes to the AthleteController class which performs validation check and based on the results, either sends the user to the player-confirmation.jsp page or back to the add-player-form.jsp for resubmission.
First, we will add the field firstName to the Athlete class along with its getter and setter methods as follows:
Making last name field "required"
The @NotNull annotation is used to ensure that a field is not null, preventing users from submitting empty values for required fields. It is part of the jakarta.validation.constraints ...