1

I'm looking to validate an URL. I have already a script that validates to not allow www. and http:// but i need to also validate for .co.uk .com etc.

My script won't run if they enter something like example.co.ukff.

I have this for a full URL:

^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i

I just need to validate the end .co.uk or .com etc.

marapet
  • 49,690
  • 10
  • 152
  • 168
iSimpleDesign
  • 373
  • 1
  • 6
  • 19

2 Answers2

4

Try This...

/^http:\/\/|(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/

It's working exactly what you want.

it takes with or with out http://, https://, and www.

  • 2
    Did you try it? It matches `http://` alone and `[a-z]{2,5}` is really poor to match TLDs, see: https://data.iana.org/TLD/tlds-alpha-by-domain.txt – Toto Oct 17 '14 at 13:01
2

Far from pretending this to be the ideal regex to match urls, the particular problem of only matching urls which do not begin with www can be resolved with a negative lookahead : (?!www\.) meaning that the following text should not be www.

Therefore, your regex adapted with this negative lookahead:

^(?!www\.)[A-Za-z0-9_-]+\.+[A-Za-z0-9.\/%&=\?_:;-]+$

matches the following urls

google.com
google.com/
goggle.com/q
google.com/q?q=1&h=en
google.co.uk
google.co.uk/
goggle.co.uk/q
google.co.uk/q?q=1&h=en
w.google.com
w.google.com/
w.goggle.com/q
w.google.com/q?q=1&h=en
209.85.149.105
209.85.149.105/
209.85.149.105/q
209.85.149.105/q?q=1&h=en
209.85.149.105:80
209.85.149.105:80/
209.85.149.105:80/q
209.85.149.105:80/q?q=1&h=en
example.domain.bogus.number.of.subdomains/index.htm

but not those:

www.google.com
www.google.com/
www.google.co.uk
www.google.co.uk/
www.google.co.uk/q
www.google.co.uk/q?q=1&h=en
http://209.85.149.105/
http://209.85.149.105:80/
http://www.google.com
https://www.google.com
http://google.com
https://google.com
marapet
  • 49,690
  • 10
  • 152
  • 168