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


CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Website development Company in Allahabad