Use Regular expression (RegEx) to validate a URL in JavaScript.
string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
URL validation in JavaScript Example
Below HTML Example, code creates a function to validate URL with or without HTTP/HTTPS. Testing a multiple condition and format URL validation in JS.
<html>
<body>
<script>
function isValidURL(string) {
var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
return (res !== null)
};
var tc1 = "http://en.wikipedia.org/wiki/Procter_&_Gamble";
console.log(isValidURL(tc1));
var tc2 = "http://www.google.com/url?sa=i&rct=j&q=&";
console.log(isValidURL(tc2));
var tc3 = "https://sdfasd";
console.log(isValidURL(tc3));
var tc4 = "dfdsfdsfdfdsfsdfs";
console.log(isValidURL(tc4));
var tc5 = "magnet:?xt=urn:btih:123";
console.log(isValidURL(tc5));
var tc6 = "https://eyehunts.com/";
console.log(isValidURL(tc6));
var tc7 = "https://w";
console.log(isValidURL(tc7));
var tc8 = "https://sdfasdp.ppppppppppp";
console.log(isValidURL(tc8));
</script>
</body>
</html>
Output:
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