2

What is the best regex that I can use for client validation of URLs of the form;

example.com:8080 (Valid)
10.15.123.14:8080 (Valid)
example.com (Invalid)
10.15.123.14 (Invalid)

The protocol "http" is not necessary/required. In fact that is not going to part of my form field.

copenndthagen
  • 46,750
  • 95
  • 274
  • 417

2 Answers2

2

I would go with something like this /^([a-z0-9\-]+\.)+[a-z0-9]+\:[1-9][0-9]+$/i

var str = [
    "Example.com:8080",
    "10.15.123.14:8080",
    "example.com",
    "10.13.123.14",
    "example!1.com:8080",
    "example-1.com:8080",
    "example!1.com:8080",
    "example\1.com:8080",
    "example1.com:8"
    ];

var regex = /^([a-z0-9\-]+\.)+[a-z0-9]+\:[1-9][0-9]+$/i;

for(var i=0; i < str.length; i++) {
    $('#test').append(regex.test(str[i])+"</br>");
}

http://jsfiddle.net/thinkingmedia/2SnhP/5/

Reactgular
  • 48,266
  • 14
  • 138
  • 193
2

Matches ip's until 255.255.255.255 and ports until 65535:

^((([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])|[a-zA-Z0-9]*):(6553[0-5]|655[0-2][0-9]\d|65[0-4](\d){2}|6[0-4](\d){3}|[1-5](\d){4}|[1-9](\d){0,3})$

Matches websites (or ip's) and ports until 65535:

^[^:]+:(6553[0-5]|655[0-2][0-9]\d|65[0-4](\d){2}|6[0-4](\d){3}|[1-5](\d){4}|[1-9](\d){0,3})$
Yannick
  • 362
  • 1
  • 9