Written by Sai Sandeep Thota on April 24, 2014 in JavaScript > Programming

JavaScript to Validate Age entered by User

GET ALERTS:

Get our Latest updates delivered to your mailbox!

This is our first article in JavaScript category. In this article we are going to explain JavaScript to validate the age entered by the user. For instance you have a web form which need to accept users of age between 18 and 25. This is a simple script which has two events, onfocus – triggers when an element gains focus and onchange – triggers when an element is changed.

We are using the onfocus event to check whether the element has gained focus, if it has gained focus then we are calling a function called displayMessage.

displayMessage() function

In this function we are searching the document for the element with id msg and manipulating the HTML inside it to display a note. You need to observe that this message is only displayed when the element gains focus.

validateAge() function

In this function we are validating the age entered by user, if it is in the specified criteria then we are returning true else false.

Demo Download Source Code

<html>
<head>
<style>
body {
background: #F4F4F4;
font-family: Arial;
}
</style>
</head>

<body>
<table border="0" style="margin: 0 auto; width:500px">
	<tr>
		<td colspan="2"><h2>Validate Age</h2></td>
	</tr>
	<tr>
		<td width="15%">Name:</td>
		<td><input type="text" id="uname" required></td>
	</tr>

	<tr>
		<td width="15%">Email:</td>
		<td><input type="text" id="email" required"></td>
	</tr>

	<tr>
		<td width="15%">Age:</td>
		<td><input type="text" id="age" onfocus="displayMessage()" onchange="return validateAge(this)" required"><span style="color:red; font-size:10px; margin-left:5px;" id="msg"></span></td>
	</tr>

	<tr>
		<td colspan="2"><button name="null">Submit</button></td>
	</tr>
</table>

<script>
function displayMessage() {
	document.getElementById("msg").innerHTML = "<strong>Note:</strong>Age must be between 18 and 25";
}

function validateAge(age) {
	var input = age.value;
	if(input>=18&&input<=25) {
		return true;
	}
	else {
		alert("Age must be between 18 and 25 | You have entered "+input);
		return false;
	}
}
</script>
</body>
</html>

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: