Regex for the validation of the file path in javascript

advertisements

I can't seem to find a Regular Expression for JavaScript that will test for the following cases:

  • c:\temp
  • D:\directoryname\testing\
  • \john-desktop\tempdir\

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.