Jquery validation input Multiple file

Asked

Viewed 169 times

1

Currently valid only file extension on input file, need valid a file multiple.

Code I have so far:

Html

<label>Arquivos .XML<br>
    <input type="file" multiple name="arquivoXML[]" id="arquivoXml" required="true" accept=".xml">
</label>

Jquery

;(function($) {
    $('#formulario').submit(function(e) {
        var file = $('#arquivoXml').val();
        var exts = ['xml'];

        if ( file ) {

            var get_ext = file.split('.');
            get_ext = get_ext.reverse();

            if ( $.inArray ( get_ext[0].toLowerCase(), exts ) > -1 ){

            } else {
                alert('Arquivo XML inválido');
                e.preventDefault();
                $("#arquivoXml").focus();
            }
        }
    });
})(jQuery);

1 answer

2


You need to take the array archival ($('#arquivoXml')[0].files) and check one by one until finalized as being all of that kind stipulated by the code, example:

;
(function($) {
  $('#formulario').submit(function(e) {
    var files = $('#arquivoXml')[0].files;
    var exts = ['xml'];
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      if (file) {
        var get_ext = file.name.split('.');
        get_ext = get_ext.reverse();
        if ($.inArray(get_ext[0].toLowerCase(), exts) > -1)         {
            continue; 
        } else {
          alert('Arquivo XML inválido');
          e.preventDefault();
          $("#arquivoXml").focus();
          return false;
        }
      } else return false;
    }
    return true;
  });
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formulario" name="formulario">
  <input type="file" id="arquivoXml" multiple accept="*.xml" />
  <button>Verificar</button>
</form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.