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.
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.
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]:)?(\\[^<>:"/\\|?*]+)+\\?$
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).
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