roman23
roman23

Reputation: 55

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>

Upvotes: 4

Views: 2293

Answers (3)

Rory McCrossan
Rory McCrossan

Reputation: 337580

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

Upvotes: 3

Anders Arpi
Anders Arpi

Reputation: 8397

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")
}

Upvotes: 0

Tim S.
Tim S.

Reputation: 13843

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.

Upvotes: 0

Related Questions