1

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

Amod Vardhan
  • 29
  • 1
  • 3
  • 10

3 Answers3

16

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.

brainbowler
  • 667
  • 5
  • 17
6

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

Pravin
  • 106
  • 1
  • 5
  • This is okay if user not typing the www. Means it will be fine if user types "https:// yahoo.i" (shows error). But if user types it like "https:// www.yahoo.i" , this will not show any error and validates. – Niladri Banerjee - Uttarpara May 29 '17 at 12:50
2

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

AnneRaNa
  • 51
  • 10