1

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

  • It is not fully clear what you need to support. Is anything starting with `/`, `./` and `../` is valid? – Yoni Levy Feb 22 '17 at 13:00
  • 1
    @YoniLevy Yes. It hast to be relative (/, ./ and ../ also count) and no special characters are allowed like $%§& –  Feb 22 '17 at 13:08
  • How the other special charachters? What if they are properly escaped? – Attila Mar 16 '18 at 10:00

3 Answers3

1

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

Yoni Levy
  • 1,562
  • 2
  • 16
  • 35
  • This would eventually "do the job", but it is not what is neeed. Please note that special characters should not be accepted. According to this your simple solution could be potentially used, but it would not be completely correct. – Attila Mar 16 '18 at 10:03
0

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:

https://regex101.com/r/fW9eM4/1

Attila
  • 3,206
  • 2
  • 31
  • 44
0

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
Tolar
  • 61
  • 4