I trying to validate user entered string is correct relative path or not.
I am trying with below regex, but it is not working correctly.
^([a-z]:)*(\/*(\.*[a-z0-9]+\/)*(\.*[a-z0-9]+))
My test cases
Valid path
Invalid path
Alternative "readable" approach ;)
public static bool IsValidPath(this string path)
{
if (string.IsNullOrEmpty(path)) return false;
if (path.StartsWith("assets/")) return false;
if (path.EndsWith("/")) return false;
if (path.Contains(".")) return false;
return true;
}
// Usage
var value = "sample/hello/images";
if (value.IsValidPath())
{
// use the value...
}
If you also want to match the underscore, you could add it to the character class. To prevent matching assets/
at the start, you could use a negative lookahead.
^(?!assets/)[a-z0-9_]+(?:/[a-z0-9_]+)+$
^
Start of string(?!assets/)
Assert what is directly to the right is not assets/
[a-z0-9_]+
Repeat 1+ times any of the listed, including the underscore(?:/[a-z0-9_]+)+
Repeat 1+ times a /
and 1+ times any of the listed $
End of stringRegex demo
Or you could use \w
instead of the character class
^(?!assets/)\w+(?:/\w+)+$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With