Spring Validation


 

Spring Validation

In this tutorial you will see an example of validation in spring framework.

In this tutorial you will see an example of validation in spring framework.

Spring Validation

In this tutorial you will see an example of how to perform validation in spring-core. The spring provide Validator interface for validation of object. The Validator inteface work parallel with the Errors object so that while validation, report validation send by validators to the Error object.

Person.java

package com.roseindia;

public class Person {
	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;
	}

}

PersonValidator.java

package com.roseindia;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

public class PersonValidator {

	public boolean supports(Class clazz) {
		return Person.class.equals(clazz);
	}

	public void validate(Object obj, Errors e) {
		System.out.println("Inside validation");
		ValidationUtils.rejectIfEmpty(e, "name", "nameEmpty");
		Person p = (Person) obj;
		if (p.getAge() < 0) {
			e.rejectValue("age", "negativevalue");
		} else if (p.getAge() > 110) {
			e.rejectValue("age", "too old");
		}
		System.out.println(e);
	}

}

AppMain.java

package com.roseindia.common;

import org.springframework.validation.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.roseindia.*;

public class AppMain {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "context.xml" });
		Person person1 = (Person) context.getBean("personBean");
		PersonValidator p = new PersonValidator();
		BeanPropertyBindingResult v = new BeanPropertyBindingResult(person1,
				"Errors");
		p.validate(person1, v);
	}
}

context.xml

<?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:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  <bean id="personBean" class="com.roseindia.Person">
    <property name="name" value="satya" />
    <property name="age" value="122" />
  </bean>
  
</beans>

When you run this application it will display message as shown below:


Inside validation
org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'Errors' on field 'age': rejected value [122]; codes [too old.Errors.age,too old.age,too old.int,too old]; arguments []; default message [null]

Download this example code

Ads