0

I'm using:

<input type='file' name='pac1[]' multiple>

How do I javascript validate that there is at least one file selected?

When using:

<input type='file' name='pac1'>

I have no problem validating a single non-array entry.

1
  • 1
    this.files.length ?
    – Rayon
    Commented Apr 20, 2016 at 5:39

2 Answers 2

2

You can use:

<input id="upload" type='file' name='pac1[]' multiple>

And JS:

if(document.getElementById("upload").files.length < 1)
{
   alert("No file selected");
   return false;
}
3
  • This worked. Thank you. Commented Apr 20, 2016 at 5:50
  • Found an issue. What if the browser (like IE8) does not support multiple? The script then fails on that length check. Commented Apr 20, 2016 at 6:16
  • Is there a solution other than checking to see if browser supports it? Commented Apr 20, 2016 at 12:43
0

Bind change event on input type='file' element using addEventListener

INPUTElement.files.length will return number of files selected.

document.querySelector('[name="pac1[]"]').addEventListener('change', function() {
  alert(this.files.length);
});
<input type='file' name='pac1[]' multiple>

2
  • The change event won't fire if there is no file selected :-) ("validate that there is at least one file selected")
    – Kaiido
    Commented Apr 20, 2016 at 5:50
  • @Kaiido, True! :P I did not consider the term "validation" :(
    – Rayon
    Commented Apr 20, 2016 at 5:52

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