简体   繁体   中英

Validate at least 1 file input is completed with jQuery

How can I ensure that at least one field has a selected file using jQuery? Here is my form:

<form action="b.php">
    <input type="file" name="file[]">
    <input type="file" name="file[]">
    <input type="file" name="file[]">
    <input type="file" name="file[]">
    <input type="submit" value="Value">
</form>

To achieve this you can use map() to build an array of all the valid file input elements. You can then check if this array has any elements in it. If it does, then at least one input was valid, if it was empty then nothing has been chosen. Try this:

var validFields = $('input[type="file"]').map(function() {
    if ($(this).val() != "") {
        return $(this);
    }
}).get();    

if (validFields.length) {
    console.log("Form is valid");
} else {
    console.log("Form is not valid");
}

Example fiddle

You could use jQuery's .val() method to check if a value has been set but I don't know if that works for file input types.

However, you should use a server-side language to validate your files because if you're using javascript, the person browsing the page can just disable the validating. Just loop through the file[] array and check if it's empty or not.

This is much safer and easier as well actually.

While you of course need server-side validation, there are some nice tricks to check if somebody has added a file to your input elements.

Now, your access to the file input element is heavily restricted due to security reasons, so you can't for example change it. You can, however, check the following:

if($('input[type="file"]').val() != "") {
    alert("a file is selected")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM