Check File Uploads - JQuery and Accept

I use the form to upload a file. I want only PDF files loaded. This is my code:

An input field that allows the user to select a file:

@Html.FileBox(m => m.FileName, new { id = "FileName", accept = "application/pdf" }) 

and place to display error messages:

 @Html.ValidationMessageFor(m=>m.FileName) 

Code generated for input field:

  <input id="FileName" type="file" name="FileName" data-val-required="The File Name field is required." data-val-length-max="512" data-val-length="The field File Name must be a string with a maximum length of 512." data-val="true" accept="application/pdf"> 

Now, even if I select a PDF file, I get an error message Please enter a value with a valid extension.

I use MVC 3 and unobstrusive jquery to validate the form.

+7
source share
4 answers

The accept method, built into jQuery validation, accepts values โ€‹โ€‹in a format similar to jpg | png.

The HTML accept attribute accepts a format similar to image / jpeg, image / png.

It seems that jQuery Validation and the HTML standard are not compatible in this regard.

Here you can learn more about the jQuery "accept" confirmation rules and the HTML5 "accept" attribute.

+7
source

I had the same problem, and I had to resort to disabling verification for the accept attribute completely. I added the following line to my page and it worked:

$. validator.addMethod ('accept', function () {return true;});

+10
source

They changed the behavior of the accept method with version 1.10.0. Instead of checking the file extension, it now looks at the mime type. Old behavior is now available as an extension method. So you just need to update the jquery validation plugin version and you're done. I replaced the current version 1.9.0 with 1.11.0 and set the valid mime types as accept-attribut. Now it works as expected:

 accept="image/*, application/pdf" 
+7
source

If you insert both formats as an accept attribute, it should work

 accept="image/jpeg,image/png,jpg|png" 
+5
source

All Articles