Scroll to top

Spring Validation Tutorial for Java beginners

Spring Validation is the combination of Validator interface and DataBinder or in other words spring achieve validation with the help of these two. Validator interface can be used  to validate an Object, which(validator interface) in turn uses Error Object to report any validator error while validating an Object.

Validator(org.springframework.validation.Validator) interface has two main methods.

  1. supports(Class)  : Class(Instance of) this validator supports to.
  2. validate(Object, org.springframework.validation.Errors) : Validate the Object and reports the validation error via Error Object


public class ContactValidator implements Validator {

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

    public void validate(Object obj, Errors e) {
        ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
        Contact c = (Contact) obj;
        if (c.getAge() < 0) {
            e.rejectValue("age", "negativevalue");


How to Re-Use Validator

There might be the case when Object in application has the reference of another Object. Like Person object has an Address property which is in itself an Object. So instead of writing(Copy and paste from Address validator) validator code for Contact you can dependency inject Address validator in Contact validator.


public class PersonValidator implements Validator {

    private final Validator contactValidator;

    public PersonValidator (Validator contactValidator) {
        if (contactValidator== null) {
            throw new IllegalArgumentException(
              "The supplied Validator is required and must not be null.");
        if (!contactValidator.supports(Contact.class)) {
            throw new IllegalArgumentException(
              "The supplied must support the validation of Contact instances.");
        this.contactValidator = contactValidator;

    * This Validator validates Person instances, and any subclasses of Persontoo
    public boolean supports(Class clazz) {
        return Person.class.isAssignableFrom(clazz);

    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "field.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "field.required");
        Person person = (Person) target;
        try {
            ValidationUtils.invokeValidator(this.contactValidator, person.getAddress(), errors);
        } finally {


Author avatar


  1. jack

    thank you very mutch i learn mutch in this website

Post a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.