Javatpoint Logo
Javatpoint Logo

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.

Validation Annotations

Let's see some frequently used validation annotations.

Annotation Description
@NotNull It determines that the value can't be null.
@Min It determines that the number must be equal or greater than the specified value.
@Max It determines that the number must be equal or less than the specified value.
@Size It determines that the size must be equal to the specified value.
@Pattern It determines that the sequence follows the specified regular expression.

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.

pom.xml

2. Create the bean class

Employee.java

3. Create the controller class

In controller class:

  • The @Valid annotation applies validation rules on the provided object.
  • The BindingResult interface contains the result of validation.

4. Provide the entry of controller in the web.xml file

web.xml

5. Define the bean in the xml file

spring-servlet.xml

6. Create the requested page

index.jsp

7. Create the other view components

viewpage.jsp

final.jsp

Output:

Spring MVC Validation

Let's submit the form without entering the password.

Spring MVC Validation

Now, we entered the password and then submit the form.

Spring MVC Validation
Spring MVC Validation

Download Hibernate Validator Jar File

If you are not using maven, download hibernate validator jar.





Please Share

facebook twitter google plus pinterest

B.Tech / MCA


Learn Latest Tutorials