Confirm at least 1 file entry completed with jQuery

How can I guarantee 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> 
+4
source share
3 answers

To do this, you can use map() to build an array of all valid input elements. Then you can check if there are any elements in this array. If so, then at least one entry was valid, if it was empty, nothing was selected. Try the following:

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

Script example

+3
source

You can use the jQuery .val() method to check if a value is set, but I don't know if this works for file input types.

However, you must use a server-side language to validate your files, because if you use javascript, the person viewing the page may simply turn off validation. Just skip the file[] array and see if it is empty or not.

It is much safer and easier, in fact.

0
source

Although you certainly need server-side validation, there are some good tricks to check if someone has added a file to your input elements.

Now your access to the file input element is severely limited due to security reasons, so you cannot change it. However, you can check the following:

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

Source: https://habr.com/ru/post/1390611/


All Articles