Reputation: 2534
I can't seem to find a Regular Expression for JavaScript that will test for the following cases:
You can see what I am going for. I just need it to validate a file path. But it seems like all the expressions I have found don't work for JavaScript.
Upvotes: 6
Views: 31083
Reputation: 22867
I've found an example here:
http://regexlib.com/Search.aspx?k=file+name&AspxAutoDetectCookieSupport=1
and I've modified it to match pathes starting with '\'
:
^((([a-zA-Z]:|\\)\\)|(\\))?(((\.)|(\.\.)|([^\\/:\*\?"\|<>\. ](([^\\/:\*\?"\|<>\. ])|([^\\/:\*\?"\|<>]*[^\\/:\*\?"\|<>\. ]))?))\\)*[^\\/:\*\?"\|<>\. ](([^\\/:\*\?"\|<>\. ])|([^\\/:\*\?"\|<>]*[^\\/:\*\?"\|<>\. ]))?$
This is clear-regex unescaped version with is easier to read (really!).
It matches pathes like:
etc.
Upvotes: 1
Reputation: 49
Here is the Windows path validation, it's works fine for all windows path rules.
var contPathWin = document.editConf.containerPathWin.value;
if(contPathWin=="" || !windowsPathValidation(contPathWin))
{
alert("please enter valid path");
return false;
}
function windowsPathValidation(contwinpath)
{
if((contwinpath.charAt(0) != "\\" || contwinpath.charAt(1) != "\\") || (contwinpath.charAt(0) != "/" || contwinpath.charAt(1) != "/"))
{
if(!contwinpath.charAt(0).match(/^[a-zA-Z]/))
{
return false;
}
if(!contwinpath.charAt(1).match(/^[:]/) || !contwinpath.charAt(2).match(/^[\/\\]/))
{
return false;
}
}
and this is for linux path validation.
var contPathLinux = document.addSvmEncryption.containerPathLinux.value;
if(contPathLinux=="" || !linuxPathValidation(contPathLinux))
{
alert("please enter valid path");
return false;
}
function linuxPathValidation(contPathLinux)
{
for(var k=0;k<contPathLinux.length;k++){
if(contPathLinux.charAt(k).match(/^[\\]$/) ){
return false;
}
}
if(contPathLinux.charAt(0) != "/")
{
return false;
}
if(contPathLinux.charAt(0) == "/" && contPathLinux.charAt(1) == "/")
{
return false;
}
return true;
}
Try to make it in a single condition.
Upvotes: 4
Reputation: 9206
I think this will work:
var reg = new RegExp("^(?>[a-z]:)?(?>\\|/)?([^\\/?%*:|\"<>\r\n]+(?>\\|/)?)+$", "i");
I've just excluded all(?) invalid characters in filenames. Should work with international filenames (I dunno) as well as any OS path type (with the exceptions noted below).
Upvotes: 1
Reputation: 6844
Try this:
([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\?
EDIT:
@Bart made me think about this regexp. This one should work nice for windows' paths.
^([a-zA-Z]:)?(\\[^<>:"/\\|?*]+)+\\?$
Upvotes: 1
Reputation: 57996
You could start with:
^([a-zA-Z]:)?(\\[a-zA-Z0-9_\-]+)+\\?
This matches all your samples.
Upvotes: 0