Validation Utils And Validator Interface Of Spring
Posted By : Manish Gupta | 31-May-2018
This blog highlights the Spring's org.springframework.validation.Validator interface. This interface can be used to validate the properties of an object and report the errors if the object property which is to be validated is found empty(null or ") and/or contains the empty spaces, for instance. The validator interface works with the Errors interface. While validating the object, the Validator interface will report the validation errors to the Errors object. The Validator uses two methods: 1) supports(Class): This is used to check if the Validator supports the given object. 2) validate( Object, org.springframework.validation.Errors ): This actually validates the given object and if any validation failure occurs when the errors are reported to the object of org.springframework.validation.Errors. To illustrate, let us create a class with the name Employee with the properties of employee first name, last name, employee id and employee age.
class Employee{
private int id;
private String fname;
private String lname;
private int age;
public int getId()
{
return id;
}
public void setId( int id )
{
this.id = id;
}
// remaining getter setters
}
public class EmployeeValidator implements Validator {
public boolean supports(Class clzz) {
return Employee.class.equals(clzz);
}
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "fname", "fname.empty");
ValidationUtils.rejectIfEmpty(e, "lname", "lname.empty");
Employee emp = (Employee)obj;
if (emp.getAge() < 18) {
e.rejectValue("age", "negativeAgeValue");
} else if (emp.getAge() > 60) {
e.rejectValue("age", "cannotParticipate");
}
}
}
We can validate any property as per the validation required on that property. Example, we can write our custom logic for password validation. ----------- Thanks -----------
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Manish Gupta
Manish is a Java Developer with hands on experience in Core Java, JSP, Spring framework, JavaScript, JQuery, HTML, CSS, and SQL/PL-SQL. Tools used: Eclipse, Netbeans, DBeaver, Oracle SQL Developer, Toad, MS SQL Server. He is a keen learner and technology