Spring MVC validation Example

Spring MVC validation Example

In the last example , we developed an MVC application.But it does not have any validations.If some validation criteria needs to meet while submitting the form , spring has the provisions to do the same. JSR-303 is the specification for been validations in Java .We are using the hibernate validator as the implementation.We are just inserting a validation in to the previous login form example.

So the work space set up and files are almost same.Some files needs to be edited.

pom.xml

The pom.xml needs to include any of the JSR-303 validation implementation.We are using hibernate-validator

loginform.jsp

It needs to include the form errors in the page so that if validation fails,it can be shown.We can give suitable css properties also , if required.

LoginController.java

It needs to render the same login page if validation fails.Otherwise the success page needs to be rendered.

User.java

The validation rules are mentioning in the command class itself.Since we are dealing with a very basic example , we are using the default validation messages which the frameworks provides by default.

dispatcher-servlet.xml 

mvc:annotation-driven is added for validations.

Output

Now lets see the output .Just run the application in server and test the page with various conditions. User id should be within 3 to 10 characters. And password should be within 10 to 20.If the entered data is not matching the requirements , then the same form with validation messages will be rendered.

validationoutput

    See Related:

Spring Overview
Spring MVC Example