I am searching for a Regular Expressions which checks if the relative URL is valid.
For example:
/somesite => valid
http://WebReference.com/experts/ => invalid. (absolute)
../experts/ => valid
I am searching for a Regular Expressions which checks if the relative URL is valid.
For example:
/somesite => valid
http://WebReference.com/experts/ => invalid. (absolute)
../experts/ => valid
Based on your needs you can simply check the start of the path
So this /^(\.\.\/|\.\/|\/)/
would do the job.
It will only allow paths stating with /
, ./
, and ../
There is a related question:
Regex check if given string is relative URL
Based on this you could eventually use:
^(?!www\.|(?:http|ftp)s?://|[A-Za-z]:\\|//).*
There is also an online demo for this regex, you can try easily:
I'll comment how I got to my result:
you want relative paths that start with '/' or '../' so I assume you'd want to accept './' as well:
(\.?){2}\/
folder-names are usually alphanumeric with underscores [a-zA-Z0-9_] but minus is usually fine too:
[a-zA-Z0-9_\-]
Foldernames have minimum one character but are not limited:
[a-zA-Z0-9_\-]+
If you wanted to limit them to 30 characters:
[a-zA-Z0-9_\-]([a-zA-Z0-9_\-]?){29}
At least one Foldername but any number above:
(\/[a-zA-Z0-9_\-]+)+
Could be limited just like the characters.
Result without limitations of name length or folder count:
/^(\.?){2}(\/[a-zA-Z0-9_\-]+)+$/
Alternatively, if you want to also accept paths that end with a slash like "/root/manuals/" you need to append /?
/^(\.?){2}(\/[a-zA-Z0-9_\-]+)+\/?$/
The leading '^' and the '$' at the end prevent the expression from matching anything like
XXXXXXXXXXXXX/root/directory_1/YYYYYYYYYYYYY