Spring MVC form validation with custom validator

In the previous post, we have seen the form validation using java validations by annotating model class with constraint validation annotations.

Good part of it is, we can just add annotations on the fields of the model class and if any errors in the form as per the annotations , Binding Result will get the errors.

But bad part of it is , we will not get annotations for all our business validations on the form fields.

Example : If we want to Validate age field to be greater than 18 and less than 60 to be allowed then we need to define our own validator.

So lets see how we can write our custom validator
We need to do following things to define our custom validator

1)Create the custom validator class for model class on which we validate and implement the validator interface, make custom validator class as spring bean.
2)Override supports(Class clazz) method
3)Override validate(Object target,Errors errors) method
4)After this we need to inject this custom validator in the controller class and call its validate() method
5)Then check the binding result for any errors and return the appropriate view.

Project structure

First will define the model class as below

  1. package com.kb.model;
  2.  
  3. import javax.validation.constraints.Size;
  4.  
  5. import org.hibernate.validator.constraints.Email;
  6. import org.hibernate.validator.constraints.NotEmpty;
  7.  
  8. public class Customer {
  9.    
  10.     @NotEmpty
  11.     @Email
  12.     private String emailId;
  13.    
  14.     @Size(min=8,max=15)
  15.     private String password;
  16.    
  17.    
  18.     @Size(min=8,max=15)
  19.     private String confPassword;
  20.    
  21.     private int age;
  22.  
  23.     public String getEmailId() {
  24.         return emailId;
  25.     }
  26.  
  27.     public void setEmailId(String emailId) {
  28.         this.emailId = emailId;
  29.     }
  30.  
  31.     public String getPassword() {
  32.         return password;
  33.     }
  34.  
  35.     public void setPassword(String password) {
  36.         this.password = password;
  37.     }
  38.  
  39.     public String getConfPassword() {
  40.         return confPassword;
  41.     }
  42.  
  43.     public void setConfPassword(String confPassword) {
  44.         this.confPassword = confPassword;
  45.     }
  46.  
  47.     public int getAge() {
  48.         return age;
  49.     }
  50.  
  51.     public void setAge(int age) {
  52.         this.age = age;
  53.     }
  54.  
  55. }
package com.kb.model;

import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;

public class Customer {
	
	@NotEmpty
	@Email
	private String emailId;
	
	@Size(min=8,max=15)
	private String password;
	
	
	@Size(min=8,max=15)
	private String confPassword;
	
	private int age;

	public String getEmailId() {
		return emailId;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getConfPassword() {
		return confPassword;
	}

	public void setConfPassword(String confPassword) {
		this.confPassword = confPassword;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

We will have the basic validation annotations to validate each field and we will use custom validator for business validation.

Note : age field is not having basic annotation @NotEmpty as I demonstrate the same inside custom validator.

Now will define custom validator as below

  1. package com.kb.validator;
  2.  
  3. import org.springframework.stereotype.Component;
  4. import org.springframework.validation.Errors;
  5. import org.springframework.validation.ValidationUtils;
  6. import org.springframework.validation.Validator;
  7.  
  8. import com.kb.model.Customer;
  9.  
  10. @Component
  11. public class CustomerValidator implements Validator {
  12.  
  13.     public boolean supports(Class<?> clazz) {
  14.         return Customer.class.isAssignableFrom(clazz);
  15.     }
  16.  
  17.     public void validate(Object target, Errors errors) {
  18.         Customer customer = (Customer)target;
  19.         int age = customer.getAge();
  20.         String password = customer.getPassword();
  21.         String confPassword = customer.getConfPassword();
  22.         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "customer.age.empty");
  23.        
  24.         //Business validation
  25.         if(!password.equals(confPassword)){
  26.             errors.rejectValue("password","customer.password.missMatch");
  27.         }
  28.         if(age < 18 || age > 60){
  29.             errors.rejectValue("age", "customer.age.range.invalid");
  30.         }
  31.    
  32.     }
  33. }
package com.kb.validator;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.kb.model.Customer;

@Component
public class CustomerValidator implements Validator {

	public boolean supports(Class<?> clazz) {
		return Customer.class.isAssignableFrom(clazz);
	}

	public void validate(Object target, Errors errors) {
		Customer customer = (Customer)target;
		int age = customer.getAge();
		String password = customer.getPassword();
		String confPassword = customer.getConfPassword();
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "customer.age.empty");
		
		//Business validation
		if(!password.equals(confPassword)){
			errors.rejectValue("password","customer.password.missMatch");
		}
		if(age < 18 || age > 60){
			errors.rejectValue("age", "customer.age.range.invalid");
		}
	
	}
}

Observe the age validation for empty or whitespace is achieved using ValidationUtils method, so we didn’t add @NotEmpty annotatin on age field in model class.

We can completely remove all the annotations on the model class and validate the fields using ValidationUtils methods and our custom validation.

Finally errors are getting added to the Binding result object.

Define the controller class as below

  1. package com.kb.controller;
  2.  
  3. import javax.validation.Valid;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.ui.Model;
  8. import org.springframework.validation.BindingResult;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RequestMethod;
  11.  
  12. import com.kb.model.Customer;
  13. import com.kb.validator.CustomerValidator;
  14.  
  15. @Controller
  16. public class RegistrationController {
  17.    
  18.     @Autowired
  19.     CustomerValidator customerValidator;
  20.    
  21.    
  22.      @RequestMapping(value = "/register", method = RequestMethod.GET)
  23.         public String viewRegistrationPage(Model model) {
  24.           Customer customer = new Customer();
  25.             model.addAttribute("customer", customer);
  26.             return "register";
  27.         }
  28.    
  29.      @RequestMapping(value = "/doRegister", method = RequestMethod.POST)
  30.         public String doLogin(@Valid Customer customer, BindingResult result,Model model) {
  31.          model.addAttribute("customer",customer);
  32.          customerValidator.validate(customer, result);
  33.           if(result.hasErrors()){
  34.               return "register";
  35.           }
  36.          
  37.           return "home";
  38.         }
  39.  
  40.     public CustomerValidator getCustomerValidator() {
  41.         return customerValidator;
  42.     }
  43.  
  44.     public void setCustomerValidator(CustomerValidator customerValidator) {
  45.         this.customerValidator = customerValidator;
  46.     }
  47.  
  48. }
package com.kb.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kb.model.Customer;
import com.kb.validator.CustomerValidator;

@Controller
public class RegistrationController {
	
	@Autowired
	CustomerValidator customerValidator;
	
	
	 @RequestMapping(value = "/register", method = RequestMethod.GET)
	    public String viewRegistrationPage(Model model) {
	      Customer customer = new Customer();
	        model.addAttribute("customer", customer);
	        return "register";
	    }
	
	 @RequestMapping(value = "/doRegister", method = RequestMethod.POST)
	    public String doLogin(@Valid Customer customer, BindingResult result,Model model) {
		 model.addAttribute("customer",customer);
		 customerValidator.validate(customer, result);
	      if(result.hasErrors()){
	    	  return "register";
	      }
	      
	      return "home";
	    }

	public CustomerValidator getCustomerValidator() {
		return customerValidator;
	}

	public void setCustomerValidator(CustomerValidator customerValidator) {
		this.customerValidator = customerValidator;
	}

}

In the above controller , we have autowired the customerValidator and called validate() method by passing model object and BindingResult object, which will validate the fields.

Create messages.properties file under WEB-INF directory

  1. NotEmpty.customer.emailId=Email Id is required.
  2. Email.customer.emailId=valid email id is required.
  3. Size.customer.password=Password should be minimum of 8 and maximum of 15 characters.
  4. Size.customer.confPassword=Password should be minimum of 8 and maximum of 15 characters.
  5. customer.age.empty = Age is required
  6. customer.age.range.invalid = Age should be between 18 to 60
  7. customer.password.missMatch = password and confirm password do not match
NotEmpty.customer.emailId=Email Id is required. 
Email.customer.emailId=valid email id is required.
Size.customer.password=Password should be minimum of 8 and maximum of 15 characters.
Size.customer.confPassword=Password should be minimum of 8 and maximum of 15 characters.
customer.age.empty = Age is required
customer.age.range.invalid = Age should be between 18 to 60
customer.password.missMatch = password and confirm password do not match

Create spring configuration file as below

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  7.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  8.        http://www.springframework.org/schema/context
  9.        http://www.springframework.org/schema/context/spring-context-3.2.xsd
  10.        http://www.springframework.org/schema/mvc
  11.        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
  12.  
  13.     <context:component-scan base-package="com.kb.*" />
  14.     <mvc:annotation-driven />
  15.  
  16.     <bean id="viewResolver"
  17.         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  18.         <property name="prefix" value="/WEB-INF/pages/" />
  19.         <property name="suffix" value=".jsp" />
  20.     </bean>
  21.  
  22.     <bean id="messageSource"
  23.         class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  24.  
  25.         <property name="basename" value="/WEB-INF/messages" />
  26.     </bean>
  27. </beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

	<context:component-scan base-package="com.kb.*" />
	<mvc:annotation-driven />

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/pages/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<bean id="messageSource"
		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">

		<property name="basename" value="/WEB-INF/messages" />
	</bean>
</beans>

Create web.xml as below

  1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  3.     version="3.1">
  4.  
  5.     <display-name>Spring MVC custom validator</display-name>
  6.  
  7.     <!-- Spring MVC dispatcher servlet -->
  8.     <servlet>
  9.         <servlet-name>mvc-dispatcher</servlet-name>
  10.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  11.         <init-param>
  12.             <param-name>contextConfigLocation</param-name>
  13.             <param-value>
  14.             /WEB-INF/spring-mvc.xml,
  15.         </param-value>
  16.         </init-param>
  17.         <load-on-startup>1</load-on-startup>
  18.     </servlet>
  19.     <servlet-mapping>
  20.         <servlet-name>mvc-dispatcher</servlet-name>
  21.         <url-pattern>/</url-pattern>
  22.     </servlet-mapping>
  23.  
  24.     <listener>
  25.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  26.     </listener>
  27. </web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>Spring MVC custom validator</display-name>

	<!-- Spring MVC dispatcher servlet -->
	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
			/WEB-INF/spring-mvc.xml,
		</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app>

Add depndencies in pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.   <groupId>Spring</groupId>
  5.   <artifactId>CustomValidation</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>CustomValidation Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.  <properties>
  11.         <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
  12.     </properties>
  13.   <dependencies>
  14.     <dependency>
  15.       <groupId>junit</groupId>
  16.       <artifactId>junit</artifactId>
  17.       <version>3.8.1</version>
  18.       <scope>test</scope>
  19.     </dependency>
  20.     <dependency>
  21.             <groupId>org.springframework</groupId>
  22.             <artifactId>spring-web</artifactId>
  23.             <version>${org.springframework.version}</version>
  24.         </dependency>
  25.  
  26.         <dependency>
  27.             <groupId>org.springframework</groupId>
  28.             <artifactId>spring-webmvc</artifactId>
  29.             <version>${org.springframework.version}</version>
  30.         </dependency>
  31.         <dependency>
  32.             <groupId>javax.servlet</groupId>
  33.             <artifactId>servlet-api</artifactId>
  34.             <version>2.5</version>
  35.             <scope>provided</scope>
  36.         </dependency>
  37.         <dependency>
  38.     <groupId>javax.servlet.jsp.jstl</groupId>
  39.     <artifactId>javax.servlet.jsp.jstl-api</artifactId>
  40.     <version>1.2.1</version>
  41. </dependency>
  42. <dependency>
  43.     <groupId>taglibs</groupId>
  44.     <artifactId>standard</artifactId>
  45.     <version>1.1.2</version>
  46. </dependency>
  47. <dependency>
  48.     <groupId>javax.validation</groupId>
  49.     <artifactId>validation-api</artifactId>
  50.     <version>1.1.0.Final</version>
  51. </dependency>
  52. <dependency>
  53.     <groupId>org.hibernate</groupId>
  54.     <artifactId>hibernate-validator</artifactId>
  55.     <version>5.0.1.Final</version>
  56.  </dependency>
  57.   </dependencies>
  58.   <build>
  59.     <finalName>SpringMVCCustomValidation</finalName>
  60.     <plugins>
  61.             <plugin>
  62.                 <groupId>org.apache.maven.plugins</groupId>
  63.                 <artifactId>maven-compiler-plugin</artifactId>
  64.                 <version>2.5.1</version>
  65.                 <configuration>
  66.                     <source>1.8</source>
  67.                     <target>1.8</target>
  68.                 </configuration>
  69.             </plugin>
  70.         </plugins>
  71.   </build>
  72. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Spring</groupId>
  <artifactId>CustomValidation</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>CustomValidation Maven Webapp</name>
  <url>http://maven.apache.org</url>
 <properties>
		<org.springframework.version>4.2.0.RELEASE</org.springframework.version>
	</properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
	<groupId>javax.servlet.jsp.jstl</groupId>
	<artifactId>javax.servlet.jsp.jstl-api</artifactId>
	<version>1.2.1</version>
</dependency>
<dependency>
	<groupId>taglibs</groupId>
	<artifactId>standard</artifactId>
	<version>1.1.2</version>
</dependency>
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.0.1.Final</version>
 </dependency>
  </dependencies>
  <build>
    <finalName>SpringMVCCustomValidation</finalName>
    <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
  </build>
</project>

Build the project and deploy the war file in Tomcat

Access below url

http://localhost:8080/SpringMVCCustomValidation/register

Don’t enter anything, just click on Register

Enter valid details but enter miss match password to check that validation

Enter valid details to register and click on Register

Now we will see how InitBinder can be injected to controller for custom validation.

When we use initBinder for our custom validator , default spring validator will no be called hence, we need to add all the validations in the custom validator.

Annotations on the Model class will not do any validation so just remove them.

  1. package com.kb.model;
  2.  
  3. import javax.validation.constraints.Size;
  4.  
  5. import org.hibernate.validator.constraints.Email;
  6. import org.hibernate.validator.constraints.NotEmpty;
  7.  
  8. public class Customer {
  9.    
  10.    
  11.     private String emailId;
  12.    
  13.    
  14.     private String password;
  15.    
  16.    
  17.    
  18.     private String confPassword;
  19.    
  20.     private int age;
  21.  
  22.     public String getEmailId() {
  23.         return emailId;
  24.     }
  25.  
  26.     public void setEmailId(String emailId) {
  27.         this.emailId = emailId;
  28.     }
  29.  
  30.     public String getPassword() {
  31.         return password;
  32.     }
  33.  
  34.     public void setPassword(String password) {
  35.         this.password = password;
  36.     }
  37.  
  38.     public String getConfPassword() {
  39.         return confPassword;
  40.     }
  41.  
  42.     public void setConfPassword(String confPassword) {
  43.         this.confPassword = confPassword;
  44.     }
  45.  
  46.     public int getAge() {
  47.         return age;
  48.     }
  49.  
  50.     public void setAge(int age) {
  51.         this.age = age;
  52.     }
  53.  
  54. }
package com.kb.model;

import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;

public class Customer {
	
	
	private String emailId;
	
	
	private String password;
	
	
	
	private String confPassword;
	
	private int age;

	public String getEmailId() {
		return emailId;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getConfPassword() {
		return confPassword;
	}

	public void setConfPassword(String confPassword) {
		this.confPassword = confPassword;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

Modify our custom validator to validate each field .

  1. package com.kb.validator;
  2.  
  3. import org.springframework.stereotype.Component;
  4. import org.springframework.validation.Errors;
  5. import org.springframework.validation.ValidationUtils;
  6. import org.springframework.validation.Validator;
  7.  
  8. import com.kb.model.Customer;
  9.  
  10. @Component
  11. public class CustomerValidator implements Validator {
  12.  
  13.     public boolean supports(Class<?> clazz) {
  14.         return Customer.class.isAssignableFrom(clazz);
  15.     }
  16.  
  17.     public void validate(Object target, Errors errors) {
  18.         Customer customer = (Customer)target;
  19.         int age = customer.getAge();
  20.         String password = customer.getPassword();
  21.         String confPassword = customer.getConfPassword();
  22.         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "emailId", "customer.emailId.empty");
  23.         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "customer.age.empty");
  24.         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "customer.password.empty");
  25.         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confPassword", "customer.confPassword.empty");
  26.        
  27.         //Business validation
  28.         if(!password.equals(confPassword)){
  29.             errors.rejectValue("password","customer.password.missMatch");
  30.         }
  31.         if(age < 18 || age > 60){
  32.             errors.rejectValue("age", "customer.age.range.invalid");
  33.         }
  34.        
  35.         if(!customer.getEmailId().matches("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")){
  36.             errors.rejectValue("emailId", "customer.emailId.invalid");
  37.         }
  38.     }
  39.  
  40. }
package com.kb.validator;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.kb.model.Customer;

@Component
public class CustomerValidator implements Validator {

	public boolean supports(Class<?> clazz) {
		return Customer.class.isAssignableFrom(clazz);
	}

	public void validate(Object target, Errors errors) {
		Customer customer = (Customer)target;
		int age = customer.getAge();
		String password = customer.getPassword();
		String confPassword = customer.getConfPassword();
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "emailId", "customer.emailId.empty");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "customer.age.empty");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "customer.password.empty");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confPassword", "customer.confPassword.empty");
		
		//Business validation
		if(!password.equals(confPassword)){
			errors.rejectValue("password","customer.password.missMatch");
		}
		if(age < 18 || age > 60){
			errors.rejectValue("age", "customer.age.range.invalid");
		}
		
		if(!customer.getEmailId().matches("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")){
			errors.rejectValue("emailId", "customer.emailId.invalid");
		}
	}

}

In the controller class , add below code

  1. @InitBinder
  2.     public void initBinder(WebDataBinder webDataBinder){
  3.         webDataBinder.setValidator(customerValidator);
  4.     }
@InitBinder
	public void initBinder(WebDataBinder webDataBinder){
		webDataBinder.setValidator(customerValidator);
	}

And remove the below code which we make an explicit call to validate

  1. customerValidator.validate(customer, result);
customerValidator.validate(customer, result);

So InitBinder will call the custom validator automatically on form submit.

So your full controller should be as below

  1. package com.kb.controller;
  2.  
  3. import javax.validation.Valid;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.ui.Model;
  8. import org.springframework.validation.BindingResult;
  9. import org.springframework.web.bind.WebDataBinder;
  10. import org.springframework.web.bind.annotation.InitBinder;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RequestMethod;
  13.  
  14. import com.kb.model.Customer;
  15. import com.kb.validator.CustomerValidator;
  16.  
  17. @Controller
  18. public class RegistrationController {
  19.    
  20.     @Autowired
  21.     CustomerValidator customerValidator;
  22.    
  23.     @InitBinder
  24.     public void initBinder(WebDataBinder webDataBinder){
  25.         webDataBinder.setValidator(customerValidator);
  26.     }
  27.    
  28.    
  29.      @RequestMapping(value = "/register", method = RequestMethod.GET)
  30.         public String viewRegistrationPage(Model model) {
  31.           Customer customer = new Customer();
  32.             model.addAttribute("customer", customer);
  33.             return "register";
  34.         }
  35.    
  36.      @RequestMapping(value = "/doRegister", method = RequestMethod.POST)
  37.         public String doLogin(@Valid Customer customer, BindingResult result,Model model) {
  38.          model.addAttribute("customer",customer);
  39.          //customerValidator.validate(customer, result);
  40.           if(result.hasErrors()){
  41.               return "register";
  42.           }
  43.          
  44.           return "home";
  45.         }
  46.  
  47.     public CustomerValidator getCustomerValidator() {
  48.         return customerValidator;
  49.     }
  50.  
  51.     public void setCustomerValidator(CustomerValidator customerValidator) {
  52.         this.customerValidator = customerValidator;
  53.     }
  54.  
  55. }
package com.kb.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kb.model.Customer;
import com.kb.validator.CustomerValidator;

@Controller
public class RegistrationController {
	
	@Autowired
	CustomerValidator customerValidator;
	
	@InitBinder
	public void initBinder(WebDataBinder webDataBinder){
		webDataBinder.setValidator(customerValidator);
	}
	
	
	 @RequestMapping(value = "/register", method = RequestMethod.GET)
	    public String viewRegistrationPage(Model model) {
	      Customer customer = new Customer();
	        model.addAttribute("customer", customer);
	        return "register";
	    }
	
	 @RequestMapping(value = "/doRegister", method = RequestMethod.POST)
	    public String doLogin(@Valid Customer customer, BindingResult result,Model model) {
		 model.addAttribute("customer",customer);
		 //customerValidator.validate(customer, result);
	      if(result.hasErrors()){
	    	  return "register";
	      }
	      
	      return "home";
	    }

	public CustomerValidator getCustomerValidator() {
		return customerValidator;
	}

	public void setCustomerValidator(CustomerValidator customerValidator) {
		this.customerValidator = customerValidator;
	}

}

Modify messages.properties as below

  1. customer.emailId.empty=Email Id is required.
  2. customer.emailId.invalid=valid email id is required.
  3. customer.password.empty=Password is required
  4. customer.confPassword.empty=Confirm Password is required
  5. customer.age.empty = Age is required
  6. customer.age.range.invalid = Age should be between 18 to 60
  7. customer.password.missMatch = password and confirm password do not match
customer.emailId.empty=Email Id is required. 
customer.emailId.invalid=valid email id is required.
customer.password.empty=Password is required
customer.confPassword.empty=Confirm Password is required
customer.age.empty = Age is required
customer.age.range.invalid = Age should be between 18 to 60
customer.password.missMatch = password and confirm password do not match

And run the project , we will get the validation messages as below again.

Download this project SpringMVCCustomValidation.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on