Home  >  Spring

Validator Interface in Spring

By Arvind Rai, July 12, 2022
On this page we will learn using Spring Validator interface.
1. The Validator interface is a validator for application-specific objects.
2. The Validator interface can be used in web tier, the data-access tier, or the whatever-tier.
3. It can be used in any layer of an application, and supports the encapsulation of validation logic.
4. It is useful for custom validation in our Spring application.

5. The Validator interface has following method declarations.
a.
boolean supports(Class<?> clazz) 
Checks if this Validator can validate instances of the supplied clazz?
Parameters:
The clazz is the class that this Validator is being asked if it can validate.
Returns:
true if this Validator can validate instances of the supplied clazz.

b.
void validate(Object target, Errors errors) 
Validates the supplied target object.
Parameters:
The target is the object that is to be validated.
The errors is the contextual state about the validation process.



Maven Dependency

pom.xml
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>1.2.7.RELEASE</version>
    </dependency> 

Create Custom Validator implementing Validator Interface

To use Validator interface, we need to create a custom validator class implementing Validator interface.
Find our custom validator class.
UserValidator.java
package com.concretepage.validator;
import java.io.IOException;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.concretepage.bean.User;

public class UserValidator implements Validator {
	private Resource location;
        @Required
        public void setLocation(Resource location) {
                this.location = location;
        }
	@Override
	public boolean supports(Class cls) {
		return User.class.equals(cls);
	}
	@Override
	public void validate(Object ob, Errors err) {
		Properties props=null;
		try {
			 props = PropertiesLoaderUtils.loadProperties(location);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String msg1 = props.getProperty("errormsg.name");
		ValidationUtils.rejectIfEmpty(err, "name", "errormsg.name",msg1);
		User user = (User)ob;
		if(user.getAge()<18){
			String msg2 = props.getProperty("errormsg.age");
			err.rejectValue("age","errormsg.age",msg2);
		}
	}
} 
PropertiesLoaderUtils : A Utility class that loads java.util.Properties.
ValidationUtils : A Utility class that has methods to invoke validator.
Errors : Keeps the error message and exposes the data-binding for any object.

Now find the User class used in demo.
User.java
package com.concretepage.bean;
public class User {
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
} 

Message Property File

messages_en.properties
errormsg.name = Name can not be blank.
errormsg.age = The age  entered is not valid.  

Create Bean for Validator

spring-app.xml
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">

  <bean id="user" class="com.concretepage.bean.User">
    <property name="name" value=""/>
    <property name="age" value="16"/>
   </bean>
   <bean id="userValidator" class="com.concretepage.validator.UserValidator">
   	    <property name="location" value="messages_en.properties"/>
   </bean>
</beans> 

Run

SpringDemo.java
package com.concretepage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.validation.MapBindingResult;
import org.springframework.validation.ObjectError;
import com.concretepage.bean.User;
import com.concretepage.validator.UserValidator;
public class SpringDemo {
   public static void main(String... args) {
    	 ApplicationContext context = new ClassPathXmlApplicationContext("spring-app.xml");
    	 User user = (User)context.getBean("user");
    	 UserValidator userValidator = (UserValidator)context.getBean("userValidator");
    	 Map<String,String> map = new HashMap<String,String>(); 
    	 MapBindingResult err = new MapBindingResult(map, User.class.getName());
    	 userValidator.validate(user, err);
    	 List<ObjectError> list = err.getAllErrors();
    	 for(ObjectError objErr : list){
    		 System.out.println(objErr.getDefaultMessage());
    	 }
    } 
} 
MapBindingResult : Acts as error holder for custom binding. It supports binding errors on Map attributes.

Find the output.
Name can not be blank.
The age  entered is not valid. 

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI










©2022 concretepage.com | Privacy Policy | Contact Us