Friday, October 28, 2022

Spring - Bean Validations

  • The process of checking data validity before using data in applications is called as Data Validations.

  • In Web Applications, there are two types of data validations. 

    1. Client Side Data Validations
    2. Server Side Data Validations

1.Client-Side Data Validations: 

  • The process of checking whether data is valid or not at client browser before submitting request to the Server is called as Client Side Data Data Validations. To perform client side data validations we will use "Java Script" Functions.

2. Server Side Data Validations: 

  • The process of checking whether data is valid or not at server after getting request from client and before using data in application logic is called as Server side data validations. To perform Server side data validations we have to use Java code explicitly.


  • If we use web Frameworks like Struts, JSF , SPring WEB MVC module then all these frameworks are able to provide their own validations services implicitly to perform data validations.
  • In Spring Core Module, to perform validations over the data after storing data in Bean objects Spring Framework has provided a predefined interface in the form of "org.springframework.validation.Validator" .

To perform bean validations in Spring applications ,we have to use the following steps.

1. Prepare a properties file with all validation messages:

  • Declare validation messages in the form of key-value pairs, where keys must be validation message code and value must be validation message.

  • Example: 
    • error.uname= User Name is required. error.password=User Password is required.

2.Prepare Validator class:

  • The main intention of the Validator class is to define all data validation logic w.r.t the bean properties.


  1. Declare a user defined class.
  2. Implement org.springframework.validation.Validator interface. 
  3. Implement the Validator interface provided methods.
  4. Declare Resource property and its setXXX() method in order to represent the name and location of the properties file where all the validation messages exist.

3)Configure Validator class in spring configuration file:

  • In the spring configuration file, we have to configure Validator class as a bean with Resource property.

4)In test application get all validation messages from MapBindingResults object[Errors] by using getAllErrors() method.


public class Employee {
	private String eid; 
	private String ename; 
	private float esal; 
	private int eage; 
	private String eemail; 
	private String emobile;


	public void getEmpDetails(){ 
		System.out.println("Employee Details"); 
		System.out.println("Employee Id :"+eid); 
		System.out.println("Employee Name :"+ename); 
		System.out.println("Employee Salary :"+esal); 
		System.out.println("Employee Email :"+eemail); 
		System.out.println("Employee Mobile :"+emobile);


error.eid.empty=Employee Id is required. 
error.eid.invalid=Invalid Employee Id.
error.ename.empty=Employee Name is required. 
error.esal.invalid=Employee Salary is Invalid.
error.eage.minage=Employee Age must not be less than 18 years. 
error.eage.maxage=Employee Age must not be greater than 30 years.
error.eemail.empty=Employee Email Id is required.
error.eemail.invalid=Employee Email Id is Invalid.
error.emobile.empty=Employee Mobile is required. 
error.emobile.invalid=Employee Mobile is Invalid.

import java.util.Properties;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class EmployeeValidator implements Validator{ private Resource resource;

	public void setResource(Resource resource){ 

	public boolean supports(Class type) { 
		return Employee.class.equals(type); 

	public void validate(Object obj, Errors errors) {
	 try {
		Properties prop = PropertiesLoaderUtils.loadProperties(resource);
		Employee emp=(Employee)obj;
		if(emp.getEid() == null || emp.getEid() == ""){
			errors.rejectValue("eid", "error.eid.empty", prop.getProperty("error.eid.empty")); 
		} else{
				errors.rejectValue("eid", "error.eid.invalid", prop.getProperty("error.eid.invalid"));

		if(emp.getEname() == null || emp.getEname() == ""){
			errors.rejectValue("ename", "error.ename.empty", prop.getProperty("error.ename.empty"));

		if(emp.getEsal() <= 0.0f ){
			errors.rejectValue("esal","error.esal.invalid", prop.getProperty("error.esal.invalid")); 

		if(emp.getEage() < 18 ){
			errors.rejectValue("eage", "error.eage.minage", prop.getProperty("error.eage.minage")); }
		else if(emp.getEage() > 30 ){
			errors.rejectValue("eage", "error.eage.maxage", prop.getProperty("error.eage.maxage"));


		if(emp.getEemail() == null || emp.getEemail() == ""){ 	
			errors.rejectValue("eemail","error.eemail.empty",prop.getProperty("error.eemail.empt y"));			
				errors.rejectValue("eemail", "error.eemail.invalid", prop.getProperty("error.eemail.invalid"));

		if(emp.getEmobile() == null || emp.getEmobile() == ""){
			errors.rejectValue("emobile", "error.emobile.empty", prop.getProperty("error.emobile.empty"));
				errors.rejectValue("emobile", "error.emobile.invalid", prop.getProperty("error.emobile.invalid"));
	} catch (Exception e) { 


	<bean id="emp" class="com.cloudtechtwitter.beans.Employee">
		<property name="eid" value=""/>
		<property name="ename" value=""/> 
		<property name="esal" value=""/> 
		<property name="eage" value=""/> 
		<property name="eemail" value=""/> 
		<property name="emobile" value=""/>
	<bean id="empValidator" class="com.cloudtechtwitter.validations.EmployeeValidator">
		<property name="resource" value="/com/cloudtechtwitter/resources/"/>

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.validation.MapBindingResult;
import org.springframework.validation.ObjectError;

public class Test {
	public static void main(String[] args)throws Exception { 
		ApplicationContext context=
			new ClassPathXmlApplicationContext("applicationContext.xml"); 

		Employee emp=(Employee)context.getBean("emp"); 

		EmployeeValidator empValidator = (EmployeeValidator)context.getBean("empValidator"); 

		Map<String, String> map = new HashMap<String, String>(); 
		MapBindingResult results = new MapBindingResult(map, ""); 
		empValidator.validate(emp, results);

		List<ObjectError> list = results.getAllErrors(); 
		for(ObjectError e: list){ 

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS