In this example you will see how to validate the user registration form that we created in the previous example. To validate the form fields all you need to do is to have a seperate UserValidator class that implements the Validator interface, override the validate() method perform all the validations. In the jsp page add form:errors tag to dispaly errors and finally you need to link the UserValidator class with the UserController class. Since the UserController class extends the SimpleFormController class the validate() method will be called automatically. Incase you would like to have the error messages in a seperate properties file then you need to create a new properties file, add all the error keys and its corresponding values and finally link it to Spring configuration file.
Here you need to override the validate method. To check mandatory condition you can use the ValidationUtils class methods like rejectIfEmptyOrWhitespace or rejectIfEmpty. These methods takes three arguments the Errors object, the property name, and the error code. Here we have the error messages in a seperate properties file so we add the error code, you can even add the error messages directly. To do any other validation you have access to the domain object, using the domain object validate the properties, incase there are errors you can use the rejectValue() method of the Errors class to add errors. Here the first argument is the property name and the second argument is the error code.
The messages.properties file contains the following error keys and values.
name.required = User Name is required
email.required = Email is required
profession.required = Profession is required
country.required = Country is required
feedback.required = Feedback is required
frameworks.required = Select at least one framework
Now add the form:errors tags in the jsp page to display the errors.