Spring MVC Form Validation - manish326/spring-mvc-demo GitHub Wiki

Spring MVC Form Validation

Spring and Validation

  • Spring version 4 and higher support Bean Validation API.
  • Simply add validaton jars to out project.

Validation Annotations

  • @NotNull
  • @Min
  • @Max
  • @Size
  • @Pattern
  • @Future/@Past

Java's standard bean Validation API

  • Java standard Bean Validation API
  • Only a specification, vendor independent...Portable
  • But we still need a implementation

Hibernate Implementation for Validation API

  • Fully compliant JSR implementation
  • Not tied to ORM or database work. Its a seperate project.
  • www.hibernate.org/validator
  • Hibernate Validator 6.x is the reference implementation Bean Validation 2.0

Add the validation Jars:

Add the below dependency into POM.xml

org.hibernate.validator

hibernate-validator-osgi

6.0.16.Final

pom

Development process

  • Add validation rules to customer class
  • display error mesages on HTML form
  • perform validation in the controller class
  • update confirmation page.

@InitBinder

  • @InitBinder Annotation works as pre-processor.
  • It will pre-process each request to our cntroller.
  • Method annotated with @InitBinder is executed.

-We will use this to trim string.

Display Custom Error Message

  • Create custom error message
  • src/resources/message.properties

Load custom messages resource in Spring config file.

/WEB-INF/spring-mvc-demo-servlet.xml

⚠️ **GitHub.com Fallback** ⚠️