Form Data Validation

Learn how to use the Hibernate Validator with Spring MVC application.

Data validation includes checking if the required fields are not left blank, numbers are within a given range, and data is entered in the correct format. The Standard Bean Validation API is the preferred approach for validation in Spring applications. We will use the Hibernate implementation of the API known as Hibernate Validator.

Hibernate Validator

The current version of Hibernate validator is Hibernate Validator 7.x. Spring 5 is not compatible with this release because of differences in package naming convention. Spring 5 uses Java EE packages starting with javax.* while Hibernate Vaildator 7 has changed package names to jakarta.*.

For this reason, we will use an older version of Hibernate Validator that use the javax.* package naming convention. The validator version that is compatible with Tomcat 7 is version 5.1.3. Newer versions of the validator, 6.2.x, can be used with Tomcat 8 or higher.

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.1.3.Final</version>
</dependency>

After adding this dependency, we can use the JSR 349 validation annotations.

Validation annotations

Different validation annotations can be used on the fields to validate the data. Hibernate implements the following JSR 349 bean validation annotations:

  • @NotNull checks if a required field is left blank.
  • @Size checks that the input matches a given number of characters or digits.
  • @Min and @Max validate that a number is within a given range.
  • @Past and @Future apply to date fields to check if the date entered is before or after the current date.
  • Regular expressions can be validated using the @Pattern annotation.

Custom validation annotations for business rules of the application can also be created.

In addition to the above-mentioned annotations, Hibernate validator also provides additional annotations like @NotEmpty, @NotBlank and @Email etc.

Spring validation support

Spring MVC provides support for different bean validation APIs; JSR 303 (EE6), JSR 349 (EE7), and JSR 380 (EE8). The specifications are backward compatible. We have configured our application to automatically detect and enable validation support.

We included the following tag in player-servlet.xml while configuring our Spring MVC Application:

<mvc:annotation-driven />

This tag lets Spring MVC detect and enable validation support provided by the bean validation API.

@Vaild annotation

We can validate a model object by using the @Valid annotation in the controller class. When the user clicks the ”Submit” button, the processForm() method is executed. The @Valid annotation makes sure that the data entered by the user passes the validation rules.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.