7

I am trying to validate URL in jQuery regular expression using below code. It is working fine with http://www and https://www

var myVariable = "http://www.example.com/2013/05/test-page-url-512-518.html";

if(/^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|www\.)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(myVariable)){
    alert("valid url");
} else {
    alert("invalid url");
}

Edit:-

Above code work perfectly to validate URL. That time my requirement was only to validate http://www and https://www

3
  • stackoverflow.com/questions/2723140/… Commented May 14, 2013 at 7:45
  • 1
    Subdomains are the third level domains that are used to organize your web site content. !so wsww. is a valid url like mail.google.com... Commented May 14, 2013 at 7:49
  • @Khaled : thanks. Now I got. It means it is valid url... Commented May 14, 2013 at 7:51

5 Answers 5

11

Check this - http://docs.jquery.com/Plugins/Validation/Methods/url

$("#myform").validate({
  rules: {
    field: {
      required: true,
      url: true
    }
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

This is better than the accepted answer. No need to write and verify the regex yourself + this doesn't only check for http:// at the beginning of the URL.
3

You want to validate your URL:

Please pass the URL in this function then this will give you true OR false.

The Function :

<script>
function isUrl(s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(s);
}

isUrl(yourURL);
</script>

Comments

2

You can change your Regex, actually there is a repetition of item i.e. http:\/\/|https:\/\/|www\.

This code will work out for you:

var myVariable = "http://www.example.com/2013/05/test-page-url-512-518.html";

if(/^(http:\/\/www\.|https:\/\/www\.)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(myVariable)){
    alert("valid url");
} else {
    alert("invalid url");
}

Comments

1

your pattern is defined as

^(http:\/\/|someting else

thus any-urls begin with "http://" would be validated.

1 Comment

yeah i mean that any-urls as "http://[sth].[sth].[sth]" (sth for something) will work fine
0

try this--->

var myVariable = "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=]|:|@)){0})(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(myVariable)) {
  alert("valid url");
} else {
  alert("invalid url");
}

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.