Regex does not work on Chrome

Asked

Viewed 108 times

2

I have the following script in which I use a jquery to validate a regular expression that matches the filenames for 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 point is that the code worked with Firefox Developer, but it doesn’t work with Chrome and Edge. Regardless of the file I enter will always give invalid file name.

  • What this regex should do?

  • I have an input on my site for uploading files. This regex does not handle the file type, only the name. Example: if the user tries to insert a file with the name Me,u! Arqu;Ivo will be an invalid filename and cannot be attached. Only az Az file will be attached _ -.

  • Weird.. I tested it here and it worked. http://jsfiddle.net/yj78v/57/

  • Test a file Example: Test.txt and a T,es! te.txt ... Will return the same message

  • @Paulohdsdare questioning him are the correct files that are entering If.

  • Correct, firefox dev works fine. if I enter a file with an invalid name it does not allow me, and if I put a valid name it allows. The problem is that Chrome does not work and even if I try to put a valid file, it says it is invalid

  • Why new RegExp('^[a-zA-Z0-9-_.]+$'); instead of /^[a-zA-Z0-9-_.]+$/? Another thing has a hyphenating after the 9, you have to escape this hyphen so: /^[a-zA-Z0-9\-_.]+$/ or better /^[\w\d\-_.]+$/

  • Thanks for the tip expensive, but with the answer from below the problem has already been solved.

Show 3 more comments

1 answer

3


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

A solution that works in both browsers is to directly access the property files of 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>
<input type="file" />
<br /><span id="msg"></span>

More details about the interface File.

  • 1

    +1 very good did not know it was because of this.

  • Right, man, it really worked. I didn’t know that either, thank you very much.

Browser other questions tagged

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