Below is an example:
- First, look the method that we will use to save the object that the user filled in the form. ( This method is in ProductController.class )
@RequestMapping(method=RequestMethod.POST)
public ModelAndView save(@Valid Produto produto,
BindingResult result, RedirectAttributes redirectAttributes){
if(result.hasErrors()){
return form();
}
productDao.save(produto);
redirectAttributes.addFlashAttribute("message","Sucess");
return new ModelAndView("redirect:products");
}
- Look, we used in the method :
result.hasErrors()
How it knows this information ?
We need implement a class where we define this validations. Firstly, we need import this implementations. Look, the dependency that we will add in pom.xml ( maven configuration file )
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
Now, we can implement it :
public class ProductValidation implements Validator {
@Override public boolean supports(Class<?> clazz) { return Product.class.isAssignableFrom(clazz); }
@Override public void validate(Object target, Errors errors) { ValidationUtils.rejectIfEmpty(errors, "title", "field.required"); ValidationUtils.rejectIfEmpty(errors, "description", "field.required"); Product product = (Product) target; if(product.getPags() <= 0){ errors.rejectValue("pags", "field.required"); } } } }
What is happening in the supports method ?
What this code does is check if the object received for validation is a signature of the Product class. Thus Spring can check if the object is an instance of that class or not.
What is missing for it start to work ?
For Spring acknowledge our validator we need to create a new method in ProductController which is InitBinder. You must create the InitBinder method which receives a WebDataBinder and it uses the addValidators method to add ProductValidation in the Spring. You must use just above this method, the @InitBinder annotation for the Spring pass to use it automatically.
@InitBinder
public void InitBinder(WebDataBinder binder) {
binder.addValidators(new ProductValidation());
}