1

I am having form which takes url as input..I want to validate it using javascript and regular expression..

it should accept

  • www.google.com
  • google.com
  • http://google.com

Please suggest me a regular expression and total code if possible for validation of url... i tried lotta url given on many forums..but couldn't get appropriate answer.. thanks in advance

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Rajesh
  • 259
  • 1
  • 3
  • 6
  • What would not be valid? – Felix Kling Jun 23 '11 at 08:19
  • Have a look at [all of these](http://stackoverflow.com/search?q=javascript+regex+validate+URL) and especially [this](http://stackoverflow.com/questions/1410311/regular-expression-for-url-validation-in-javascript) and [this](http://stackoverflow.com/questions/3058138/is-it-safe-to-validate-a-url-with-a-regexp) one. – Felix Kling Jun 23 '11 at 08:21
  • Your second example is going to ruin your regex requirements; you're going to be left with something like `/\w\.\w/` – vol7ron Sep 08 '13 at 13:53
  • There is a closed question which addresses this. [http://stackoverflow.com/questions/226505/question-about-url-validation-with-regex](http://stackoverflow.com/questions/226505/question-about-url-validation-with-regex) – bhagyas Jun 23 '11 at 08:02

4 Answers4

1

try this,

^(http\://)?[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$

this will support

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
mathi
  • 1,127
  • 12
  • 19
  • The code above will fail a lot of tests for edge cases. When detecting URLs, it's ALWAYS better to rely on a specialized library. [Here's why](http://stackoverflow.com/a/21925491/1269037). – Dan Dascalescu Feb 21 '14 at 05:55
0

You can test it easily with jQuery :

http://docs.jquery.com/Plugins/Validation/Methods/url.

cynddl
  • 121
  • 2
  • 6
0

try dis

url_reg = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
K6t
  • 1,821
  • 1
  • 13
  • 21
  • "dis" code above will fail a lot of tests for edge cases. When detecting URLs, it's ALWAYS better to rely on a specialized library. [Here's why](http://stackoverflow.com/a/21925491/1269037). – Dan Dascalescu Feb 21 '14 at 05:55
0

This one would be fine, (http|https|)(://|)([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

Try it here. works fine - http://www.regular-expressions.info/javascriptexample.html

Ashwin Krishnamurthy
  • 3,750
  • 3
  • 27
  • 49
  • The code above will fail a lot of tests for edge cases. When detecting URLs, it's ALWAYS better to rely on a specialized library. [Here's why](http://stackoverflow.com/a/21925491/1269037). – Dan Dascalescu Feb 21 '14 at 05:54