It’s hard to imagine a web-application which doesn’t has some validation
 logic for an user data. Almost all user’s data has some constraints, 
e.g. date of birth should consist of day, month, year etc. Spring MVC 
has its own solution for the data validation, and it’s become available 
with the help of 
Validator interface.
Usage of Spring MVC Validator
A validation make sense in time
 when you receive some kind of data from users. An obvious way to do 
this is to use web forms. The 
Validator interface it is a means to implement the validation logic of entire Spring MVC application. Sounds promising.
There are three things which you need to do in order to start using the Validator:
- Create a validator class for some domain model and implment the Validator interface.
- Overload supports(Class clazz) method.
- Overload validate(Object target, Errors errors) method.
Now you know the basics of the 
Validator interface usage. Enough of theory let’s go ahead with practice.
Exapmle of Vlidator Spring MVC
I want to demonstrate the 
Validator
 interface in action on one of my previous tutorials where a validation 
will not be redundant. I mean the sample application with 
Spring Data. First you need to update the pom.xml file, add the following dependency:
| 03 |             <groupid>javax.validation</groupid> | 
 
| 04 |             <artifactid>validation-api</artifactid> | 
 
| 05 |             <version>1.0.0.GA</version> | 
 
| 08 |             <groupid>org.hibernate</groupid> | 
 
| 09 |             <artifactid>hibernate-validator</artifactid> | 
 
| 10 |             <version>4.3.0.Final</version> | 
 
 
 
In the project I have the one POJO:
| 02 |     @Table(name = "shops")   | 
 
| 11 |         @Column(name = "employees_number")   | 
 
| 12 |         privateInteger emplNumber;   | 
 
| 14 |         publicInteger getId() {   | 
 
| 18 |         publicvoidsetId(Integer id) {   | 
 
| 22 |         publicString getName() {   | 
 
| 26 |         publicvoidsetName(String name) {   | 
 
| 30 |         publicInteger getEmplNumber() {   | 
 
| 34 |         publicvoidsetEmplNumber(Integer emplNumber) {   | 
 
| 35 |             this.emplNumber = emplNumber;   | 
 
 
 
So let’s create the validation rules for it:
- The “name” can’t be empty.
- The “emplNumber” can’t be empty.
- The “emplNumber” can’t be less then 1.
The validation class for these purposes will look like:
| 01 | importorg.springframework.stereotype.Component; | 
 
| 02 | importorg.springframework.validation.Errors; | 
 
| 03 | importorg.springframework.validation.ValidationUtils; | 
 
| 04 | importorg.springframework.validation.Validator; | 
 
| 06 | importcom.spr.model.Shop; | 
 
| 09 | publicclassShopValidator implementsValidator { | 
 
| 11 |     privatefinalstaticString EMPLOYEES_NUMBER = "emplNumber"; | 
 
| 14 |     publicbooleansupports(Class clazz) { | 
 
| 15 |         returnShop.class.isAssignableFrom(clazz); | 
 
| 19 |     publicvoidvalidate(Object target, Errors errors) { | 
 
| 20 |         Shop shop = (Shop) target; | 
 
| 22 |         Integer emplNumber = shop.getEmplNumber(); | 
 
| 24 |         ValidationUtils.rejectIfEmpty(errors, "name", "shop.name.empty"); | 
 
| 25 |         ValidationUtils.rejectIfEmpty(errors, EMPLOYEES_NUMBER, "shop.emplNumber.empty"); | 
 
| 27 |         if(emplNumber != null&& emplNumber < 1) | 
 
| 28 |             errors.rejectValue(EMPLOYEES_NUMBER, "shop.emplNumber.lessThenOne"); | 
 
 
 
Notice
 that I applied @Component annotation to the class because I’m planning 
to inject it later into the ShopController. Here are an explanation of 
the Validator’s methods:
supports(Class) – Can this Validator 
validate instances of the supplied Class? validate(Object, 
org.springframework.validation.Errors) – validates the given object and 
in case of validation errors, registers those with the given Errors 
object. For the additional information look at the javadoc of 
ValidationUtils class. The messages which will be shown during validation should be placed in the “messages.properties” file:
| 1 | shop.name.empty = The "Shop name"field can't be empty. | 
 
| 2 | shop.emplNumber.empty = The "Employees number"field can't be empty. | 
 
| 3 | shop.emplNumber.lessThenOne = The number of employees can't be lessthen1. | 
 
 
 
Let’s move to the controller’s code:
| 03 |     privateShopValidator shopValidator; | 
 
| 06 |     privatevoidinitBinder(WebDataBinder binder) { | 
 
| 07 |         binder.setValidator(shopValidator); | 
 
| 10 |     @RequestMapping(value="/create", method=RequestMethod.POST) | 
 
| 11 |     publicModelAndView createNewShop(@ModelAttribute@ValidShop shop, | 
 
| 13 |             finalRedirectAttributes redirectAttributes) { | 
 
| 15 |         if(result.hasErrors()) | 
 
| 16 |             returnnewModelAndView("shop-new"); | 
 
| 18 |         ModelAndView mav = newModelAndView(); | 
 
| 19 |         String message = "New shop "+shop.getName()+" was successfully created."; | 
 
| 21 |         shopService.create(shop); | 
 
| 22 |         mav.setViewName("redirect:/index.html"); | 
 
| 24 |         redirectAttributes.addFlashAttribute("message", message);    | 
 
 
 
The
 code snippet above demonstrates the main things which you need to 
perform in a controller layer in order to implement the validation:
- Autowiring of the validator.
- Adding of the validator to the InitBinder.
- Apply @Valid annotation to the model in the concrete controller.
And finally let’s look at the JSP:
| 04 | <form:formmethod="POST"commandname="shop"action="${pageContext.request.contextPath}/shop/create.html"> | 
 
| 09 | <td><form:inputpath="name"></form:input></td> | 
 
| 10 | <td><form:errorspath="name"cssstyle="color: red;"></form:errors></td> | 
 
| 13 | <td>Employees number:</td> | 
 
| 14 | <td><form:inputpath="emplNumber"></form:input></td> | 
 
| 15 | <td><form:errorspath="emplNumber"cssstyle="color: red;"></form:errors></td> | 
 
| 18 | <td><inputvalue="Create"type="submit"></td> | 
 
 
 
Pay your attention on the form:errors tags, they are responsible for the displaying of the error messages.
 
Summary
The
 Validator interface allows creation of the flexible validation layer 
for each domain model object in your application. It’s a good 
alternative for the standard JSR-303 validation annotations such as 
@Min, @Max, @NotNull, @Size etc.