Paolo Broccardo
Paolo Broccardo

Reputation: 1744

Modify regex used to validate URL to allow IP addresses

A developer that did work for me wrote a Regular expression that checks for valid urls when a user enters an url. It is working really well so far, except for the fact that it doesn't recognise IP addresses.

url = url.match(/(http\:\/\/)?[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\S*)?/)

Correct:

Given: http://www.mywebsite.com/index.cfm?do=something
Result: http://www.mywebsite.com/index.cfm?do=something

Incorrect:

Given: http://64.200.10.50/index.cfm?do=something
Result: http://index.cfm?do=something

Should be: http://64.200.10.50/index.cfm?do=something

How would I modify the regex to account for IP addresses as well?

Thanks

Upvotes: 2

Views: 3670

Answers (1)

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99919

easy solution: just allow everything except / and whitespaces between https:// and the first /. That way you will also support single level domain names, ipv6 addresses, etc

/^https?\:\/\/[^\/\s]+(\/.*)?$/

Upvotes: 4

Related Questions