Validating url using javascript

Some times we might need to check if the url entered by the user in the text box is a valid one or not. Here is a sample code to check that.

<html>
<head>
<script>
function checkUrl()
{
var theUrl=document.getElementById(‘url’).value;

if(theUrl.match(/^(http|ftp)\:\/\/\w+([\.\-]\w+)*\.\w{2,4}(\:\d+)*([\/\.\-\?\&\%\#]\w+)*\/?$/i) ||

theUrl.match(/^mailto\:\w+([\.\-]\w+)*\@\w+([\.\-]\w+)*\.\w{2,4}$/i))
{
alert(“valid Url”);
}
else
{
alert(“Not valid Url”);
document.getElementById(‘url’).focus();
return false;
}
}
</script>
</head>
</body>
<form name=”frmurlvalidation”>
Your URL:<input value=”http://” name=”url” size=”50″>
<input type=”button” value=”Validate”>
</form>
</body>
</html>

Posted in Javascript Tagged with: ,