JavaScript: Basic form validation

This is a follow-up article to a previous article about basic DOM manipulation with JavaScript which you might want to read if you’re new to JavaScript.

The simplest way to get the element from the document object using the getByElementId() method and then checking the value property of the element:

var name = document.getElementById("Name");

This finds the element with the ID Name and put it in the variable name. We can now use the element to validate it. The following code is an example of how to check that the name isn’t empty and that the age is numeric and above 0. If there is an error it wil return false and color the background of the faulty input box red:

index.htm

<!DOCUMENT html>
<html>
	<head>
		<title>Javascript DOM manipulation Example</title>
		<script type="text/javascript" src="demo.js"></script>
	</head>
	<body>
		<h1>Javascript form validation test!</h1>
		<form id="MyForm" onsubmit="return validateForm()">
			<p>Name: <input type="text" id="Name" /></p>
			<p>Age: <input type="text" id="Age" /></p>
			<p><input type="submit" id="Submit" value="Submit"/></p>
		</form>
	</body>
</html>

demo.js

function validateName(name)
{
	if(name == "" || name == null || name === "undefined")
	{
		return false;
	}
	
	//Name must be more than one letter
	if(name.length <= 1)
	{
		return false;
	}
	
	return true;
}

function validateAge(age)
{
	if(age == "" || age == null || age === "undefined")
	{
		return false;
	}
	
	if(isNaN(age))
	{
		return false;
	}
	
	if(parseInt(age) <= 0)
	{
		return false;
	}
	
	return true;
}

function validateForm()
{
	//Check name
	var name = document.getElementById("Name");
	var isNameOk = validateName(name.value);
	console.log(name);
	
	if(isNameOk)
	{
		name.style.background = "#FFFFFF";
	}
	else
	{
		name.style.background = "#FF0000";
	}
	
	//Check age
	var age = document.getElementById("Age");
	var isAgeOk = validateAge(age.value);
	
	if(isAgeOk)
	{
		age.style.background = "#FFFFFF";
	}
	else
	{
		age.style.background = "#FF0000";
	}

	return isNameOk && isAgeOk;				
}

We hook up to the onsubmit event on the form element in HTML and we return the value we get from the validation method validateForm. If we return false the form won’t submit and that’s why we alter the form and color it, so that the user can identify where the errors are. This can be made even better by adding text or something but in this demo we’ll keep it simple.

Try a demo here if you want!