6

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.

Ronak Patel
  • 3,324
  • 4
  • 21
  • 31
postalservice14
  • 2,515
  • 4
  • 25
  • 33
  • What would you do with a file path in JS? Normally JS doesn't have any access to local disk file system. Sending the file path to server side would also not make much sense as the server doesn't have any access to the client's local disk file system. After all I think you just need `input type="file"` and don't worry about validation. – BalusC Jan 09 '10 at 01:06
  • 1
    BalusC, I understand this. The application I am creating is dealing with a database server which has filepaths as one of it's fields. In order for it to be edited, I would like to have some validation. Even though the user could potentially put in an invalid path, at least this will help in making sure the user puts in a path at all. Also, this is a server-side path, so input type="file" will not work. Thanks. – postalservice14 Jan 10 '10 at 09:42

5 Answers5

4

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.

Brian J
  • 694
  • 1
  • 21
  • 34
Kiran Kumar
  • 49
  • 1
  • 2
1

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:

  • c:\temp
  • \temp
  • ..\my folder
  • üöä

etc.

Danubian Sailor
  • 1
  • 38
  • 145
  • 223
1

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]:)?(\\[^<>:"/\\|?*]+)+\\?$
Gaim
  • 6,734
  • 4
  • 38
  • 58
  • That matches an empty string as well. Also note that folders in Windows can have more than the set `[a-zA-Z0-9_-]` in them. – Bart Kiers Jan 08 '10 at 20:00
  • +1 because I feel better when I see somebody else which writes regexs like mines; I'm "normal" after all – Rubens Farias Jan 08 '10 at 20:00
  • @Bart You are right, thanks. I'll fix it. Note: I know but it is simply editable. I wrote base regex - idea is clear – Gaim Jan 08 '10 at 20:01
  • I haven't tested it, but it looks like this excludes paths that start with numbers and other non-alphabetic characters? – EricP Sep 09 '12 at 22:04
  • 1
    @Joe Why should it? The first group is for drive letter in Windows like `C:`. In URI structure you can think about it as about a scheme. The rest of the regex matches the resource path including numbers and non-alphabetic characters. There are explicitly mentioned forbidden characters only. Note: It matches absolute paths, based on the question – Gaim Sep 10 '12 at 05:24
1

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

Kevin Peno
  • 9,107
  • 1
  • 33
  • 56
  • Sorry but some of your excluded chars are allowed, for example `% [ ]` – Gaim Jan 08 '10 at 20:13
  • % was defined on the wiki page I linked as a wildcard on one system, thus, for compatability, it was not allowed. I've updated to remove [] from the disallow list though. – Kevin Peno Jan 08 '10 at 20:18
  • @Kevin I am using Linux Ubuntu ( Jaunty ) and % there is allowed character. So I can have a file which doesn't match your regexp ( I know, usage of there characters is ugly but we don't know nothing about future customers ) – Gaim Jan 08 '10 at 20:22
  • Like I said, it's not globally valid per the wiki page, so I added it to the rule list. If the character in question does not matter in your risk assessment, remove it :) See: http://en.wikipedia.org/wiki/Filename – Kevin Peno Jan 08 '10 at 20:25
  • The regexps are very tricky and I really don't know if they are the technologies of the bright or of the dark side of the code :) I've found 2 things that don't function: first, the capital letters for drive names are not accepted (trivial to fix). Second, it DOES accept the pathes like 'a:b' which are illegal, this is because the construction of second part with relation to the optionality of the third... and I have no idea how to fix it... – Danubian Sailor Dec 07 '12 at 08:58
  • @lechlukasz can you point to where C:c, or anything similar, is actually illegal? – Kevin Peno Dec 07 '12 at 21:44
0

You could start with:

^([a-zA-Z]:)?(\\[a-zA-Z0-9_\-]+)+\\?

This matches all your samples.

Rubens Farias
  • 57,174
  • 8
  • 131
  • 162