Spring Validation

Spring’s features a Validator interface that you can use to validate objects. The Validator interface works using an Errors object so that while validating, validators can report validation failures to the Errors object. Let’s consider a small data object:

public class Person {
private String name;
private int age;
// the usual getters and setters...
}

We’re going to provide validation behavior for the Person class by implementing the following two methods of the org.springframework.validation.Validator interface:

  1. supports(Class) – Can this Validator validate instances of the supplied Class?
  2. validate(Object, org.springframework.validation.Errors) – validates the given object and in case of validation errors, registers those with the given Errors object Implementing a Validator is fairly straightforward, especially when you know of the ValidationUtils helper class that the Spring Framework also provides.
public class PersonValidator implements Validator {
/**
* This Validator validates just Person instances
*/
public boolean supports(Class clazz) {
return Person.class.equals(clazz);
}
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
Person p = (Person) obj;
if (p.getAge() < 0) {
e.rejectValue("age", "negativevalue");
} else if (p.getAge() > 110) {
e.rejectValue("age", "too.darn.old");
}
}
}

As the static rejectIfEmpty(..) method on the ValidationUtils class is used to reject the ‘name’ property if it is null or the empty string.

Validation errors are reported to the Errors object passed to the validator. In case of Spring Web MVC can use <spring:bind/> tag to inspect the error messages.

Data binding is useful for allowing user input to be dynamically bound to the domain model of an application  Spring provides the so-called DataBinder to do exactly that. The Validator and the DataBinder make up the validation package, which is primarily used in but not limited to the MVC framework.

  


Mathematics, Technology and Programming are my passion. I am a part of Java Ecosystem and through this blog, I contribute to it. I am here to blog about my interests, views and experiences. I am on Google+ and Facebook. I feel proud to be listed as a "National Memory Record Holder" in the Limca Book of Records, 2009 and have attempted for an International Memory record in the Guiness Book of Records. I can remember the value of PI upto 10,000 digits after the decimal (3.1415.....). You can contact me on javagenious.com(At)gmal.com ; I would like to hear from you :)

Share This Post

Related Articles

Powered by WordPress · Designed by Theme Junkie
You might also likeclose