5

I'm trying to loop through all file input fields and set an error message if any are over 5MB as a first step to form validation.

I'm using a click event on the submit button. The problem is that "key" is not defined.

This form can have up to 10 file input fields, added via AJAX called images[]

        /* loop through all file inputs to check size */
        $("#my-form").find("input[type='file']").each(function(key, value) {
            var el = this.files[key];
            if(el.size > 5242880 || el.fileSize > 5242880) {
                errorMessage = 'Files must be less than 5MB.';
            }
        });

If I use this.files[0] I can get the first field's size, but having trouble looping through all elements. Appreciate your input or other solutions. Thanks much!

1 Answer 1

8

You could do this

$("#my-form").find("input[type=file]").each(function(index, field){
   const file = field.files[0];
   if(file.size > 5242880 || file.fileSize > 5242880) {
      errorMessage = 'Files must be less than 5MB.';
   }
});

Here is a fiddle: https://jsfiddle.net/kmm67nLz/

For file inputs with multiple attribute

$("#my-form").find("input[type=file]").each(function(index, field){
  for(var i=0;i<field.files.length;i++) {
    const file = field.files[i];
    if(file.size > 5242880 || file.fileSize > 5242880) {
      errorMessage = 'Files must be less than 5MB.';
      alert(errorMessage);
    }
  }
});

Here is a fiddle: https://jsfiddle.net/kmm67nLz/1/

The second one is perfect to use in any of single or multiple file input.

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

5 Comments

I don't have an problem getting the first key [0], it's the ones after. Your fiddle only works on the first one.
I've just checked it works for 2 files in 2 separate inputs. May be I don't understand what exactly you're asking for. Is it about multiple file input?
Leave the first one blank and only add a file to your 2nd input.
That goes to error handling, just skip it or do whatever you want if you find the variable file undefined.
I see you added a for loop to your fiddle. Let me update my code tomorrow and I think this will work.

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.