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.

2
  • 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. Commented Jan 9, 2010 at 1: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. Commented Jan 10, 2010 at 9:42

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This check will fail with paths containing a minus char "-"
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]:)?(\\[^<>:"/\\|?*]+)+\\?$

5 Comments

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.
+1 because I feel better when I see somebody else which writes regexs like mines; I'm "normal" after all
@Bart You are right, thanks. I'll fix it. Note: I know but it is simply editable. I wrote base regex - idea is clear
I haven't tested it, but it looks like this excludes paths that start with numbers and other non-alphabetic characters?
@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
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).

6 Comments

Sorry but some of your excluded chars are allowed, for example % [ ]
% 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 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 )
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: en.wikipedia.org/wiki/Filename
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...
|
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.

Comments

0

You could start with:

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

This matches all your samples.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.