2

I want to allow the user to upload only pdf files in two input files:

<form onsubmit='return checkExt()' action='upload.php' method='POST'>
    <label>upload the first file</label>
    <input type='file' name='fileToUpload' id='fileToUpload' required>

    <label>upload the secondfile</label>
    <input type='file' name='fileToUpload1' id='fileToUpload1' required>
</form>

I used the following script to check the extension of the files-to-upload:

<script>
    function checkExt() {
        var allowedFiles = [".pdf"];
        var form_valid = document.getElementById("fileToUpload");
        var form_valid2 = document.getElementById("fileToUpload1");
        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");

        if (!regex.test((form_valid.value.toLowerCase()) &&(form_valid2.value.toLowerCase()))) {
            alert('only PDF files are allowed');
            return false;
        }
        return true;
    }
</script>

the problem is: when I test it, it only checks on the first file if it is a pdf or not. it does not check on the second file.

Serving Quarantine period
  • 66,345
  • 10
  • 43
  • 85
user2148116
  • 185
  • 1
  • 2
  • 11

2 Answers2

0

You don't need javascript to validate the filetypes. Just use to accept attribute in the input tag.

See documentation here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file

<input name="myFile" type="file" accept=".pdf" multiple>
Nisarg
  • 13,121
  • 5
  • 31
  • 48
0

Your second check in the if condition should mirror the first one and this is the reason why it doesn't work. Anyway the easiest and scalable way is to iterate over input fields of type "file". Like this:

function checkExt() {
  var fileInputs = document.querySelectorAll('input[type="file"]');
  var isValid = true;
  var allowedFiles = [".pdf"];
  var regex = new RegExp(
    "([a-zA-Z0-9s_\\.-:])+(" + allowedFiles.join("|") + ")$"
  );

  fileInputs.forEach(function(input) {
    if (!regex.test(input.value.toLowerCase())) {
      isValid = false;
    }
  });

  if (isValid) {
    alert("only PDF files are allowed");
  }

  return isValid;
}

This allows you to add as many file input fields as you want.

lukaleli
  • 2,867
  • 3
  • 18
  • 31