Programming Examples
JavaScript code to validate an IP address given by user.
Write a JavaScript code to validate an IP address given by user.
Solution
<!DOCTYPE HTML>
<html>
<head>
<title>IP Address Validation</title>
<style type="text/css">
.result_spn
{
color:#00ff00;
font-size:20px;
}
.error_spn
{
color:#ff0000;
font-style:italic;
}
</style>
<script language="javascript">
function validate_ip()
{
var chkdate = document.getElementById("ip_txt").value;
document.getElementById("error").innerHTML="";
document.getElementById("result").innerHTML="";
if(document.getElementById("ip_txt").value == "")
{
document.getElementById("error").innerHTML="Please enter the IP Address";
document.getElementById("ip_txt").focus();
}
else if(!chkdate.match(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/))
{
document.getElementById("error").innerHTML="IP Address format is wrong";
document.getElementById("ip_txt").focus();
}
else
{
document.getElementById("result").innerHTML="This is Valid IP Address";
}
}
</script>
</head>
<body>
<form name="frm" id="frm">
<div>
<label for="dob">Enter the IP Address</label>
<input type="text" name="ip_txt" id="ip_txt"/>
<span id="error" class="error_spn">*</span>
</div>
<div>
<input type="button" name="check_btn" id="check_btn" value="validate" onclick="validate_ip()"/>
</div>
<div>
<span id="result" class="result_spn"></span>
</div>
</form>
</body>
</html>
Output