2

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.

1

3 Answers 3

17

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.