Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 398
Amod Vardhan Avatar asked Mar 27 '26 18:03

Amod Vardhan


2 Answers

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.

like image 108
brainbowler Avatar answered Mar 31 '26 08:03

brainbowler


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

like image 44
Pravin Avatar answered Mar 31 '26 08:03

Pravin