Javascript Regex For Validating Filenames
Solution 1:
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 namesreturnfunctionisValid(fname){
return rg1.test(fname)&&!rg2.test(fname)&&!rg3.test(fname);
}
})();
isValid('file name');
Solution 2:
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.
Solution 3:
You need to anchor the expression by using ^
and $
. For example:
/^[-\w^&'@{}[\],$=!#().%+~ ]+$/
Note that you need to escape -
in a character class, or place it first/last.
Solution 4:
/^(?!\.)(?!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 notend with .
Solution 5:
Since this post (regex-for-windows-file-name) redirects to this question, I assume its about windows file names.
And based on the comment and reference by @Leon on the answer by @AndrewD, I made this regular expression and it works for me.
/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$|([<>:"\/\\|?*])|(\.|\s)$/ig
According to the naming-conventions (see reference above), I agree that "com0" should be a valid file name, but its not working if you try to name a file "com0" on windows, so I guess thats missing in the article.
So this regular expression would be more safe
/^(con|prn|aux|nul|com[0-9]|lpt[0-9])$|([<>:"\/\\|?*])|(\.|\s)$/ig
Post a Comment for "Javascript Regex For Validating Filenames"