Javascript validate a field that allows for multip

2020-03-26 00:52发布

问题:

I have a form that allows for multiple file uploads.

<input name="uploadedfile[]" type="file" multiple="true"/>

Now, I want to validate it using javascript to check if a file was selected. I tried the following but failed

if(form.uploadedfile.length < 1)
{
    alert("You Forgot to select an image");
    return false;
}

and I know its an array but i also tried

if(form.uploadedfile.value == '')
{
    alert("You Forgot to select an image");
    return false;
}

can someone help me out on this one. Thanks

回答1:

In this example they use a files property of the input, and check the length of that, something like this.

<input name="uploadedfile[]" id="uploadfile" type="file" multiple="true"/>

And the JS:

if(document.getElementById("uploadfile").files.length < 1)
{
   alert("You Forgot to select an image");
   return false;
}

Haven't been able to find any info about the files-property yet.



回答2:

One approach is:

$('input[type="file"][multiple]').change(
    function(e){
        var numFiles = e.currentTarget.files.length;
        if (numFiles == 0){
            // no files
        }
        else {
            // files chosen
            console.log(numFiles);
        }
        return false;
    });

JS Fiddle.