Amod Vardhan Amod Vardhan - 3 months ago 16
jQuery Question

url validation jquery using regex

I want to validate URL field something like below -


  1. http://www.example.com

  2. http://example.com

  3. www.example.com



First two are validation using below regex -

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);
}


but, when i am putting scenario 3 in textbox it showing me invalid URL.

Any help will be highly appreciated.

Thanks in Advance

Amod

Answer

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