0

I am using jquery validation plugin for validating my form. I have one file field in form for uploading documents.

<input type="file" name="policyBriefFiles" id="policyBriefFiles" multiple="multiple">

Here is my validation code for this field.

policyBriefFiles: {
         extension:'xlsx,pdf',
         filesize: 2097152,  
     },

Now I want users to select maximum two files, but with multiple attribute specified with file user can select any number of files.

How do I restrict users to select maximum two files and no more? Is there any rule available in jquery validation plugin for this? (like maxFile: 2)

I don't mind any other workaround also.

6
  • I think this link can help you: stackoverflow.com/questions/8212041/…
    – Jonathan
    Commented Mar 22, 2016 at 6:59
  • @DoanMinhTien Thanks for your answer. In the link they are validating file size. I want to validate number of files selected. Commented Mar 22, 2016 at 8:03
  • 1
    you can do something like it: document.getElementById('policyBriefFiles').files.length to get number of files after user selected
    – Jonathan
    Commented Mar 22, 2016 at 8:09
  • Yup. That worked. Thanks. Commented Mar 22, 2016 at 8:52
  • 1
    "Is there any rule available in jquery validation plugin" ~ why not first check the documentation or look at the source code of the plugin and the additional-methods file?
    – Sparky
    Commented Mar 23, 2016 at 1:41

2 Answers 2

1

I made custom validation method for this. Here it is

$.validator.addMethod("maxFilesToSelect", function(value, element, params) {
    var fileCount = element.files.length;
    if(fileCount > params){
        return false;
    }
    else{
        return true;
    }
},  'Select no more than 2 files');

And specify rule as

policyBriefFiles: {
         extension:'xlsx,pdf',
         filesize: 2097152,  
         maxFilesToSelect : 2,
     },

Working as charm :-)

0

We can simple add maxfiles: 3 method which is available in the additional-method.js file of the plugin. maxfiles: 3 // no of max files you want.

Not the answer you're looking for? Browse other questions tagged or ask your own question.