Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for file path validation in javascript

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.

like image 980
postalservice14 Avatar asked Jan 08 '10 19:01

postalservice14


3 Answers

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.

like image 100
Kiran Kumar Avatar answered Nov 19 '22 17:11

Kiran Kumar


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]:)?(\\[^<>:"/\\|?*]+)+\\?$
like image 38
Gaim Avatar answered Nov 19 '22 17:11

Gaim


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).

like image 1
Kevin Peno Avatar answered Nov 19 '22 16:11

Kevin Peno