Spring MVC Validation
The Spring MVC Validation is used to restrict the input provided by the user. To validate the user's input, the Spring 4 or higher version supports and use Bean Validation API. It can validate both server-side as well as client-side applications.
Bean Validation API
The Bean Validation API is a Java specification which is used to apply constraints on object model via annotations. Here, we can validate a length, number, regular expression, etc. Apart from that, we can also provide custom validations.
As Bean Validation API is just a specification, it requires an implementation. So, for that, it uses Hibernate Validator. The Hibernate Validator is a fully compliant JSR-303/309 implementation that allows to express and validate application constraints.
Let's see some frequently used validation annotations.
Spring MVC Validation Example
In this example, we create a simple form that contains the input fields. Here, (*) means it is mandatory to enter the corresponding field. Otherwise, the form generates an error.
1. Add dependencies to pom.xml file.
2. Create the bean class
3. Create the controller class
In controller class:
4. Provide the entry of controller in the web.xml file
5. Define the bean in the xml file
6. Create the requested page
7. Create the other view components
Let's submit the form without entering the password.
Now, we entered the password and then submit the form.
Download Hibernate Validator Jar File
If you are not using maven, download hibernate validator jar.