tags:

views:

59

answers:

2

can someone tell me the javascript regular expression for physical path like

1) User Should enter something like this in the textbox( c://Folder1/) . Maybe in d: or e:

2) But after that acceptable

a) (c://Folder1/Folder2/)

b) (d://Folder1/Folder2/Folder3/abc.txt)

e) (c://Folder1/Folder2/Folder3/abc.txt)

+1  A: 

From the examples you've given, something like this should work:

[a-zA-Z]://(\w+/)+

ie:
[a-zA-Z] = a single letter (upper or lower case)
followed by
:// = the characters "://"
followed by:
(\w+/)+ = at least one "something/".
"something/" defined as :
\w+ = at least one word character (ie any alphanumeric), followed by
/ = literal character "/"

Hope this helps - my syntax may be a little off as I'm not fully up to speed on the javascript variant for regex.

Edit: put regex in code tags so it is visible! And tidy up explanation.

sam
+1. slashes need to be escaped in JS regular expression literals (altho to be fair we don't really know that we're dealing with a regex literal). but overall, this seems like a reasonable approach.
David Hedlund
Interesting - I didn't know that. So presumably wherever I put "/" it should be "\/"?
sam
@sam: well, you don't have to if you write `new RegEx("[a-z]/")` but in javascript, there's a shorthand for regular expression, that is `/`, just as surrounding something in quotes is shorthand-ish for `new String("a")`. so `var a = new RegEx("[a-z]", "g")` is often written as `var a = /[a-z]/g` and *then* you of course have to escape `/` with `\/`
David Hedlund
+1  A: 

This problem is actually trickier than you think. You're trying to validate a path, but paths can be surprisingly hard to properly validate. Are you properly handling UNC network paths, e.g.?

This is known as the canonicalization problem and is part of writing secure code. I suggest checking out some guidance from Microsoft for properly canonicalizing and validating the path in your application. The advantage of canonicalizing your path is that you also implicitly validate its format because the canonical form will be returned from a library call that will only return paths that are potentially valid (properly formatted). This means that you don't have to do any sort of regex validation at all. Just throw your string at the method that canonicalizes the path (Path.GetFullPath() probably) and handle the exception for an invalid path.

Greg D
Well very good point you made i will furthur see to it
mazhar kaunain baig