Javascript reexpression to validate file names

I have a regex for checking file names. Here he is:

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

It should resolve file names as follows:

 aaa aaa.ext a# A9#.ext 

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

The problem is that file names such as *.txt or /\kk are checked. I am checking with the keyup event. Therefore, when I put one extra character after it was not allowed, it shows that everything is correct.

+11
javascript regex
source share
6 answers

You need to add a starting anchor:

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

This says that the engine should match the beginning of the input to the end of the input, whereas for your original expression it should match only at the end of the input.

+8
source share

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'); 
+28
source share

You need to bind the expression with ^ and $ . For example:

 /^[-\w^&'@{}[\],$=!#().%+~ ]+$/ 

Note that you need to exit from - to the character class or put it first / last.

+7
source share
 /^(?!\.)(?!com[0-9]$)(?!con$)(?!lpt[0-9]$)(?!nul$)(?!prn$)[^\|\*\?\\:<>/$"]*[^\.\|\*\?\\:<>/$"]+$/ Must not be empty. Must not start with . Must not be com0-com9, con, lpt0-lpt9, nul, prn Must not contain | * ? \ : < > $ Must not end with . 
+2
source share

I would try something with this Regex (you can even make a validation attribute for ASP.NET MVC with it!):

 @"^[^\u0022\u003C\u003E\u007C\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\u0009\u000A\u000B\u000C\u000D\u000E\u000F\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001A\u001B\u001C\u001D\u001E\u001F\u003A\u002A\u003F\u005C\u002F]*$" 

If it matches the input, it is a valid file name (at least on Windows).

0
source share

Since this post (regex-for-windows-file-name) is redirected to this question, I assume its Windows file names.

And based on the comment and @Leon's link to @AndrewD's answer, I made this regex and it works for me.

 /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$|([<>:"\/\\|?*])|(\.|\s)$/ig 

According to the naming conventions (see Link above), I agree that “com0” should be a valid file name, but it does not work if you try to name the file “com0” on windows, so I assume this is not in article

So this regex will be safer

 /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$|([<>:"\/\\|?*])|(\.|\s)$/ig 
0
source share

All Articles