[Java] – How to validate a form using validation of Spring?

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 )
public ModelAndView save(@Valid Produto produto, 
        BindingResult result,  RedirectAttributes redirectAttributes){
        return form();
    return new ModelAndView("redirect:products");
  • Look, we used in the method : 

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 )


  Now, we can implement it :

public class ProductValidation implements Validator {
    public boolean supports(Class<?> clazz) {
        return Product.class.isAssignableFrom(clazz);
    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.

    public void InitBinder(WebDataBinder binder) {
        binder.addValidators(new ProductValidation());



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s