MVC 3 input file Client-side validation for required

A simple question ... Can I use client-side MVC 3 checking on file type inputs?

To explain: MVC 3 uses its model validation using IClientValidatable and unobtrusive javascript so that you can write server-side validation and render the client side using jquery validation using Microsoft plugins. To make the required property you add the attribute below

[Required] public HttpPostedFileBase CvFile {get; set;} 

As long as the client val command and unobtrusive javascript are included in the config, all of this should work on the client.

However, HttpPostedFileBase (i.e. <input type="file" name="Model.CvFile" />) will not be executed on the client side.

Any ideas on how this can be achieved while keeping in touch with server-side validation

+7
source share
2 answers

Simple answer: A HttpPostedFileBase displays the input type β€œfile”, which is a security issue, and AFAIK is not scriptable. There is no support for this out of the box.

Edit: This seems to be a very popular topic on the Internet. http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx

+1
source

You need to add it manually:

 <input type="file" data-val="true" data-val-required="please select a file" name="file" /> @Html.ValidationMessage("file") 
+27
source

All Articles