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/… 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 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? 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 :-)

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.