Spring MVC Form Custom Validation

Facebooktwitterredditpinterestlinkedinmailby feather

We have discussed earlier the other forms of Validation, such as Regular Expression and Number Validations. Spring Validation also offers a user to perform Custom Validations. It allows us to create our annotation, which will be used to implement the validation rules. For example, a field collegeCode is taken for custom validation and a ConstraintValidator, which is used to validate the collegeCode checks whether it starts with the word “TIPS” or not.

In the example of custom Validation, we are going to use the following annotations:

  • @Constraint The @Constraint annotation is used to mark an annotation as a Bean Validation Constraint. It is available in javax.validation package.
  • @Target – The @Target annotation indicates the text on which the annotation type is applicable. It is available in the java.lang.annotation package.
  • @Retention – The @Retention annotation indicates that how long the annotation is to be retained with the provided annotated type. It is available in java.lang.annotation package.

Let’s understand the concept of custom validation with the help of an example.

Directory Structure of Custom validation

Spring MVC Form Custom Validation

Example of Custom Validation

Here, we are going to create an example of Custom validation.

Following are the steps to create an example of custom validation:

  • Create a request page

In this step, we are going to create a request page index.jsp.

index.jsp

  • Create the Model class

In this step, we are going to create the Model class Customer.java, which stores the form data.

Customer.java

  • Create the Controller class

In this step, we are going to create a Controller class MainController.java, which returns the JSP view pages.

MainController.java

  • Create the Validator annotation

In this step, we are going to create the validator annotation for the application. Our validator annotation is CollegeCode, which is going to annotate the collegeCode field.

CollegeCode.java

  • Create the Validator class

In this step, we are going to create a validator class named Clge_CodeConstraintValidator, which contains the validation code.

Clge_CodeConstraintValidator.java

  • Add the entry of Controller in the web.xml

In this step, we are going to add the entry of the Controller in the web.xml.

web.xml

  • Define the Model into another XML file

In this step, we are going to add the entry of Model class in another XML file (spring-servlet.xml).

spring-servlet.xml

  • Create all the view pages

In this step, we are going to create all the view pages (JSP pages) required in the application.

customerform.jsp

customerformdata.jsp

Output

Spring MVC Form Custom Validation 1
Spring MVC Form Custom Validation 2
Spring MVC Form Custom Validation 3
Spring MVC Form Custom Validation 4
Spring MVC Form Custom Validation 5
Facebooktwitterredditpinterestlinkedinmailby feather