0

Possible Duplicate:
What is the best regular expression to check if a string is a valid URL?

I wanted to validate URL taken from the user. Like http://www.google.com I wanted to validate last part of the URL (.com) I am continuously searching on the web but not found a correct answer. My code is:

function validate()
{
    var url = document.getElementById("url").value;

    var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
    

    if (pattern.test(url)) {
        alert("Valid Url");
        return true;
    } 
        alert("Please Input Right URL");
        return false;

}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Akki
  • 9
  • 3
  • @user1875558 : Please see ash's comment it will give you some idea.And look into this link for validating url http://answers.oreilly.com/topic/280-how-to-validate-urls-with-regular-expressions/ – karthick Dec 11 '12 at 11:20

1 Answers1

1
function ValidURL(str) {
   var pattern = new RegExp('^(https?:\/\/)?'+ // protocol
      '((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name
      '((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address
      '(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ // port and path
      '(\\?[;&a-z\d%_.~+=-]*)?'+ // query string
      '(\#[-a-z\d_]*)?$','i'); // fragment locater
   if(!pattern.test(str)) {
      alert("Please enter a valid URL.");
      return false;
   } else {
      return true;
   }
}
ValidURL('google.com');

check on your console

vusan
  • 5,221
  • 4
  • 46
  • 81