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

JavaScript to Validate Age entered by User


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

body {
background: #F4F4F4;
font-family: Arial;

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

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

		<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>

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

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;

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: