views:

29

answers:

1

Here's my code -

  function Validate_URL(url) {
      var iurl = url.value;
      var v = new RegExp();
      v.compile("/^(((ht|f){1}(tp:[/][/]){1})|((www.){1}))[-a-zA-Z0-9@:%_\+.~#?&//=]+$/;");
      if (!v.test(iurl.value)) {
          url.style.backgroundColor = 'yellow';
      }
      return true; 
  }

no matter what i put in url, say http://www.abc.com/newpage.html, it returns false. how come?

+4  A: 

When you're using the constructor, you don't include the beginning and ending /. In this case, you're not using any dynamic strings, so you can use a JavaScript regex literal.

Thus, it's better to do something like:

var v = /pattern/;

The {1} is always redundant, as are the character classes when you have only one element. . needs to be escaped outside character classes. There's no reason to special-case www. It's just one possible subdomain. I don't know why you have a double / in the character class. There are other issues, such as allowing @ and # everywhere. You don't have to escape + inside a character class. You also have a stray semi-colon at the end.

There are numerous other questions about this, including What is the best regular expression to check if a string is a valid URL, Checking for a valid url using Javascript Regular Expressions, and url validation using javascript.

Matthew Flaschen