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

 Example

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.

Example

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 {
            errors.pushNestedPath("address");
            ValidationUtils.invokeValidator(this.contactValidator, person.getAddress(), errors);
        } finally {
            errors.popNestedPath();
        }
    }
}

 

By | 2017-07-21T19:36:22+00:00 June 17th, 2012|Spring|0 Comments

About the Author:

Leave A Comment