URL validation in JavaScript

In this Example we will validate a URL format using a regular expression in JavaScript.

URL validation in JavaScript

URL validation in JavaScript

In this tutorial we are going to discuss, how to validate a URL in JavaScript. Java Script is a Scripting language. A Java Script language is a lightweight programming language. JavaScript code are written into the html page. Using Java Script we are going to validate a URL, entered in the text box by user. URL validation is done by using regular expression.

Now, what is regular expression?, regular expression is an object that describe a pattern of characters. You can use a pattern to search what you enter in the text. Regular expression is user for pattern matching on text. Now in this section we are develop a program which validate the URL enter by user.

Syntax for the regular expression :

var pat = pattern;

pattern specifies the pattern matching character. And pat is a name of the regular expression.

Example : Using this example you can understand how to validate a URL in Java Script. First create a html page in which we create a text box. Using the text box user enter the URL and after clicking the button it will validate the URL. The regular expression "http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?" is used for validation purpose. It works with full qualified URL address but it wont works when you not use http. Like "www.roseIndia.net" will not work because the Url is not started with http, but when you type "http://www.roeseIndia.net" it will display a message "Valid URL".
So, what we have done is setting  the default  value of text box as http:\\, when you execute the program text box is having default value http:\\.

Now, here is the code for URL validation.

<html>
<head>
<script type="text/javascript">
function checkUrl()
{
var Url=document.getElementById('url').value;
if(http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?
{
alert("Valid Url");
}
else
{
alert("Not valid Url");
document.getElementById('url').focus();
return false;
}
}
// ]]></script>
</head>
<body bgcolor="#C0C0C0">
<form name="url-validate">
Enter URL: <input type="text" id="url" name="url" size="50" value="http://" />
<input type="button" onClick="checkUrl();" value="Validate" />
</form>
</body>
</html>

Output from the program.

When you enter wrong URL, then the output will be as follows:

Download Source Code