Regex does not work in chrome

2

I have the following script in which I use a jquery to validate a regular expression that filters the names of the files to upload:

$(document).on('change', "input[type='file']", function() {
         var validaFile = $("input[type='file']").val();

        if (validaFile != '') {
            var regex = RegExp('^[a-zA-Z0-9-_.]+$');

            if (!regex.test(validaFile)) {
                $("input[type='file']").val('');
                alert("O nome deste arquivo é inválido. Por favor renomeie o arquivo.");
                return;
            } 
        }
    });

The issue is that the code worked with Firefox Developer, but it does not work on Chrome and Edge. Regardless of the file I enter it will always give invalid filename.

    
asked by anonymous 02.12.2015 / 17:52

1 answer

3

The problem is that Chrome adds C:\fakepath\ before the filename.

One solution that works in both browsers is to directly access the files property. of the input:

$(document).on('change', "input[type='file']", function() {
  // acessa diretamente o objeto do input
  var validaFile = $(this)[0].files[0].name;

  if (validaFile != '') {
    var regex = new RegExp('^[a-zA-Z0-9-_.]+$');

    if (!regex.test(validaFile)) {
      $("input[type='file']").val('');
      $('#msg').html("O nome deste arquivo é inválido. Por favor renomeie o arquivo.");
      return;
    } else {
      $('#msg').html('O nome do arquivo é válido!');
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="file" />
<br /><span id="msg"></span>

More details on the interface File .

    
02.12.2015 / 18:39