5 file fields, 1 validation for all

Viewed 29

I have 5 file inputs that I perform a file validation using the following code:

$("#fileinput").change(function() {
        var file = this.files[0];
        var fileType = file.type;
        var match = ['application/pdf', 'image/jpeg', 'image/png', 'image/jpg'];
        if(!((fileType == match[0]) || (fileType == match[1]) || (fileType == match[2]) || (fileType == match[3]) || (fileType == match[4]) || (fileType == match[5]))){
                Swal.fire("Erro: Invalid file format!", "Only: PDF, JPG, JPEG e PNG", "error");
                $("#docpessoal").val(null);
                $(".custom-file-label").text('Selecionar documento...');
                return false;
        }
});

Instead of repeating the function for each file input I would like to to use the same function but changing the selector ID based on which input the user clicked. (I'm not sure if it's possible)

Heres the code that I tried to do that:

var nomeInput = '_';
    $('input[type="file"]').click(function(){
    var nomeInput = $(this).attr('id');
});

I tried to use the variable nomeInput in the .change selector but it doesn't work. Is there anyway to achieve that?

1 Answers

Delegate the change event to the form, in the handler, get a reference to the changed input via the event object, you don't need any messy identifiers or DOM traversing in the handler function. Like this:

$('.validate-form').on('change', '[type="file"]', e => {
  const type = e.target.files[0].type;
  if (!/application\/pdf|image\/jpe?g|image\/png/.test(type)) {
    console.log('Filetype doesn\'t match.');
  } else {
    console.log('Accepted filetype.')
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="validate-form">
  <input name="dummy">
  <br>
  <input type="file" name="file[]">
  <input type="file" name="file[]">
  <input type="file" name="file[]">
  <input type="file" name="file[]">
  <input type="file" name="file[]">
</form>

If the form contains file inputs you don't want to validate, group the wanted inputs with a class, and attach the listener using that class instead of more general attribute selector.

Related