[Solved] jQuery Validate File Upload

I am trying to validate a HTML file upload using jQuery Validate

I found I can use the meta option like:

   meta: "validate"

<input type="file" name="upload" class="{validate:{required:true,accept:'docx?|pdf'}}" />

But it does not appear to work. I need to add the required class anyways. Then the file type check will not work too of course. Do I need to do something additional?

Solution #1:

If you want to use jQuery’s validate to check the size of the file, you can do so by doing the following :

1- load the additional methods file

<script src=""></script>

2- add a custom method to validate the file size

$.validator.addMethod('filesize', function(value, element, param) {
    // param = size (in bytes) 
    // element = element to validate (<input>)
    // value = value of the element (file name)
    return this.optional(element) || (element.files[0].size <= param) 

3- use the newly added method as a validation rule to validate your input:

    rules: { inputimage: { required: true, extension: "png|jpe?g|gif", filesize: 1048576  }},
    messages: { inputimage: "File must be JPG, GIF or PNG, less than 1MB" }

Note: using the “accept” validation rule instead of “extension” result in MIME type error messages when you upload a file with a blank file type.

Respondent: Naoise Golden

Solution #2:

You can add a validation method to accomplish

    jQuery.validator.addMethod("uploadFile", function (val, element) {

          var size = element.files[0].size;

           if (size > 1048576)// checks the file more than 1 MB
               console.log("returning false");
                return false;
           } else {
               console.log("returning true");
               return true;

      }, "File type error");

And Use it like this –

      rules: {
           image: {
              required: true,

I hope this will help you..

Respondent: PHP CODER

Solution #3:

Have you read and tried it this way: ?

I mean rather than adding the validate rules to the class have you tried to just instantly add them in validate init?

Respondent: Pehmolelu

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy