Bean Validations

Bean Validations

In this tutorial, we are going to discuss bean validations in the spring framework. The process of checking data validity before using data in applications is called 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 the client browser before submitting a request to the Server is called 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 the server after getting a request from the client and before using data in application logic is called Server-side data validations. To perform Server-side data validations, we have to use Java code explicitly.

Note

If we use web Frameworks like Struts, JSF, Spring WEB MVC modules, then all these frameworks can 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 then 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.

E.g. message.properties

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.

Steps:

  • Declare a user-defined class.
  • Implement org.springframework.validation.Validator interface.
  • Implement the following Validator interface provided methods.
    • public boolean supports(Class type)
    • public void validate(Object obj, Errors errors)
  • Where supports(–) method will check whether the Bean object is supporting data validations or not.
  • Where validate(—) can include data validation logic to perform data validations.
  • Where “Errors” can include all validation messages in the form of Map object to display, to add an error message to Errors object, we have to use the “rejectValue(—-)” method.
  • Declare Resource property and its setXXX() method 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 the Validator class as a bean with Resource property.
  • In test application get all validation messages from MapBindingResults object [Errors] by using getAllErrors() method.

E.g

package com.ashok.spring.core.bean.validator.beans;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class Employee {
   private String eid;
   private String ename;
   private float esal;
   private int eage;
   private String eemail;
   private String emobile;

   public String getEid() {
      return eid;
   }

   public void setEid(String eid) {
      this.eid = eid;
   }

   public String getEname() {
      return ename;
   }

   public void setEname(String ename) {
      this.ename = ename;
   }

   public float getEsal() {
      return esal;
   }

   public void setEsal(float esal) {
      this.esal = esal;
   }

   public int getEage() {
      return eage;
   }

   public void setEage(int eage) {
      this.eage = eage;
   }

   public String getEemail() {
      return eemail;
   }

   public void setEemail(String eemail) {
      this.eemail = eemail;
   }

   public String getEmobile() {
      return emobile;
   }

   public void setEmobile(String emobile) {
      this.emobile = emobile;
   }

   @Override
   public String toString() {
      return "Employee [eid=" + eid + ", ename=" + ename + ", esal=" + esal + ", eage=" + eage + ", eemail=" + eemail
            + ", emobile=" + emobile + "]";
   }
}
package com.ashok.spring.core.bean.validator.validations;

import java.util.Properties;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.ashok.spring.core.bean.validator.beans.Employee;

public class EmployeeValidator implements Validator {
   private Resource resource;

   public void setResource(Resource resource) {
      this.resource = resource;
   }

   @Override
   public boolean supports(Class type) {
      System.out.println("Hello");
      return Employee.class.equals(type);
   }

   @Override
   public void validate(Object obj, Errors errors) {
      try {
         System.out.println("Employee Data validation started..!!");
         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 {
            if (!emp.getEid().startsWith("DSS-")) {
               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.empty"));
         } else {
            if (!emp.getEemail().endsWith("@gmail.com")) {
               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"));
         } else {
            if (!emp.getEmobile().startsWith("91-")) {
               errors.rejectValue("emobile", "error.emobile.invalid", prop.getProperty("error.emobile.invalid"));
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
<?xml version="1.0" encoding="UTF-8"?>
<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="emp"
  class="com.ashok.spring.core.bean.validator.beans.Employee">
  <property name="eid" value="" />
  <property name="ename" value="" />
  <property name="esal" value="0.0" />
  <property name="eage" value="15" />
  <property name="eemail" value="" />
  <property name="emobile" value="" />
 </bean>
 <bean id="empValidator"
  class="com.ashok.spring.core.bean.validator.validations.EmployeeValidator">
  <property name="resource" value="com/ashok/spring/core/bean/validator/config/message.properties" />
 </bean>
</beans>

message.properties

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 s= Employee Mobile is Invalid.
package com.ashok.spring.core.bean.validator.test;

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.ashok.spring.core.bean.validator.beans.Employee;
import com.ashok.spring.core.bean.validator.validations.EmployeeValidator;
/**
 * 
 * @author Ashok Kumar
 *
 */
public class TestSpringApplication {
   @SuppressWarnings("resource")
   public static void main(String[] args) {
      String configFile = "/com/ashok/spring/core/bean/validator/config/applicationContext.xml";
      ApplicationContext context = new ClassPathXmlApplicationContext(configFile);
      Employee emp = (Employee) context.getBean("emp");
      emp.toString();
      EmployeeValidator empValidator = (EmployeeValidator) context.getBean("empValidator");
      Map<String, String> map = new HashMap<>();
      MapBindingResult results = new MapBindingResult(map, "com.ashok.spring.core.bean.validator.beans.Employee");
      empValidator.validate(emp, results);
      List<ObjectError> list = results.getAllErrors();
      for (ObjectError e : list) {
         System.out.println(e.getDefaultMessage());
      }
   }
}

Output

Employee Data validation started..!!
Employee Id is required.
Employee Name is required.
Employee Salary is Invalid.
Employee Age must not be less than 18 years.
Employee Email Id is required.
Employee Mobile is required.
Bean Validations
Scroll to top