URL validation in JavaScript | Example code

Use Regular expression (RegEx) to validate a URL in JavaScript.

string.match(/(http(s)?:\/\/.)?(www\.)?[[email protected]:%._\+~#=]{2,256}\.[a-z]{2,6}\b([[email protected]:%_\+.~#?&//=]*)/g);

URL validation in JavaScript Example

Below Example, code creates a function to validate URL with or without HTTP/HTTPS. Testing a multiple condition and format URL validation in JS.


		function isValidURL(string) {
			var res = string.match(/(http(s)?:\/\/.)?(www\.)?[[email protected]:%._\+~#=]{2,256}\.[a-z]{2,6}\b([[email protected]:%_\+.~#?&//=]*)/g);
			return (res !== null)

		var tc1 = "http://en.wikipedia.org/wiki/Procter_&_Gamble";

		var tc2 = "http://www.google.com/url?sa=i&rct=j&q=&";

		var tc3 = "https://sdfasd";

		var tc4 = "dfdsfdsfdfdsfsdfs";

		var tc5 = "magnet:?xt=urn:btih:123";

		var tc6 = "https://eyehunts.com/";

		var tc7 = "https://w";

		var tc8 = "https://sdfasdp.ppppppppppp";


URL validation in JavaScript

Note that per RFC 3886, URL must begin with a scheme (not limited to http/https), e. g.:

  • www.example.com is not a valid URL (missing scheme)
  • javascript:void(0) is a valid URL, although not an HTTP one
  • http://.. is valid URL with the host being .. (whether it resolves depends on your DNS)
  • https://example..com is valid URL, same as above

Do comment if you have any doubts and suggestions on this JS URL validation code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.