Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex for validating filenames

I have a regexp to validate file names. Here is it:

/[0-9a-zA-Z\^\&\'\@\{\}\[\]\,\$\=\!\-\#\(\)\.\%\+\~\_ ]+$/

It should allow file names like this:

aaa
aaa.ext
a#
A9#.ext

The following characters are not allowed \ / : * ? \" < > |

The problem is that file names like *.txt or /\kk passes the validation. I am doing validation with keyup event. So when I put one extra character after not allowed one it shows that everything is correct.

like image 433
Rafael Sedrakyan Avatar asked Jun 19 '12 12:06

Rafael Sedrakyan


2 Answers

For Windows names.

var isValid=(function(){
  var rg1=/^[^\\/:\*\?"<>\|]+$/; // forbidden characters \ / : * ? " < > |
  var rg2=/^\./; // cannot start with dot (.)
  var rg3=/^(nul|prn|con|lpt[0-9]|com[0-9])(\.|$)/i; // forbidden file names
  return function isValid(fname){
    return rg1.test(fname)&&!rg2.test(fname)&&!rg3.test(fname);
  }
})();

isValid('file name');
like image 78
Andrew D. Avatar answered Oct 10 '22 04:10

Andrew D.


You need to add a starting anchor:

/^[0-9a-zA-Z ... ]+$/

This tells the engine to match from the start of the input all the way to the end of the input, whereas for your original expression it only needs to match at the end of the input.

like image 21
Mattias Buelens Avatar answered Oct 10 '22 05:10

Mattias Buelens