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.
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');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With