Spring's org.springframework.validation.Validator interface is used to validate objects. The Validator interface is very simple and works with Errors object.

Following two methods are provided by the Validator interface.

supports(Class) - indicates whether or not this validator supports the given object.

validate(Object, org.springframework.validation.Errors) - validates the given object and in case of validation errors, put those in the given Errors object.

Example:

This example will show the implementation of Validator interface.

Consider the following Company class.

Company.java

public class Company {

  private String name;
  private int strength;

  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getStrength() {
    return strength;
  }
  public void setStrength(int strength) {
    this.strength = strength;
  }
}

Following class CompanyValidator.java is the Validator for the Company.java class. It will validate the value of strength field from 0 to 100000.

CompanyValidator.java

 public class CompanyValidator implements Validator {

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