Search code examples
springhibernatevalidationmultipartform-datahibernate-validator

How to validate a MultipartFile using HibernateValidator?


I have a field of type MultipartFile in a backing bean which is bound to a Spring form (I'm using MultipartFilter),

<form:form htmlEscape="false" action="${pageContext.request.contextPath}/admin_side/Category.htm" id="dataForm" name="dataForm" method="post" commandName="categoryBean" enctype="multipart/form-data">

    <input type="file" id="txtCatImage" name="txtCatImage"/>

</form:form>

Backing Bean,

final public class CategoryBean
{
     private MultipartFile txtCatImage=null;

     public MultipartFile getTxtCatImage()
     {
          return txtCatImage;
     }

     public void setTxtCatImage(MultipartFile txtCatImage)
     {
         this.txtCatImage = txtCatImage;
     }
}

I have tried to apply annotations like @NotEmpty but didn't work. They ended up with an exception.

javax.validation.UnexpectedTypeException: No validator could be found for type: org.springframework.web.multipart.MultipartFile

I'm using Validation-API 1.0.0. Is this possible to perform a validation, if a user doesn't upload a file and press a submit button using HibernateValidator?


Solution

  • Now I understand what you are trying to accomplish specifically. Well you could implement your own custom validation. For example, instead of implementing the Spring validator interface, implement a Hibernate ConstraintValidator, for a specific annotation that you define for this specific case. Check this link. In this case you could add an implementation for a @NotNull validator for a MultipartFile object.