Amod Vardhan
Amod Vardhan

Reputation: 39

url validation jquery using regex

I want to validate URLs of the following form:

  1. http://www.example.com
  2. http://example.com
  3. www.example.com
function is_valid_url(url) {
    return /^http(s)?:\/\/(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(url);
}

1 and 2 are validated correctly. But 3 shows an invalid URL.

Upvotes: 2

Views: 26113

Answers (3)

AnneRaNa
AnneRaNa

Reputation: 51

We need to validate n number of scenarios for URL validation. If your particular about your given pattern then above regex expression from other answer looks good. that is :

    function is_valid_url(url) 
{
   return /^(http(s)?:\/\/)?(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(url);
}

Or

If you want to take care of all the URL validation scenarios please refer In search of the perfect URL validation regex

Upvotes: 2

Pravin
Pravin

Reputation: 106

Try this, It worked for me.

var url = $("#<%= txtUrl.ClientID %>").val();
var pattern = /^(http|https)?:\/\/[a-zA-Z0-9-\.]+\.[a-z]{2,4}/;

args.IsValid = pattern.test(url);

http://www.tricksofit.com/2013/12/regular-expression-with-jquery-validation#highlighter_290011

Upvotes: 6

brainbowler
brainbowler

Reputation: 675

That's the correct regular expression for your use case:

function is_valid_url(url) {
    return /^(http(s)?:\/\/)?(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(url);
}

If "http://" is optional, you will have to put it in brackets and add a question mark.

Upvotes: 17

Related Questions