Validating Text Input

To perform basic validation on one or more input boxes of the text variety within a form, we must first start by adding all our necessary event listeners, and global variables.


Note that I intentionally chose not to call our createEventListeners() function directly, as we will be adding additional code to our setUpPage() function in the next tutorial.

"use strict"; // interpret document contents in JavaScript strict mode

/* global variables */
var formValidity = true;

/* create event listeners */
function createEventListeners() {
var form = document.getElementsByTagName("form")[0];
	if (form.addEventListener) {
	form.addEventListener("submit", validateForm, false);
	} else if (form.attachEvent) {
	form.attachEvent("onsubmit", validateForm);
	}
}

function setUpPage() {
createEventListeners();

}

/* run setup function when page finishes loading */
if (window.addEventListener) {
window.addEventListener("load", setUpPage, false);
} else if (window.attachEvent) {
window.attachEvent("onload", setUpPage);
}

Above our createEventListeners() function we can add our main validation function which uses a parameter name and begins with an if/else statement that prevents the event that called it from executing, in this case our on submit event. Below that we reset our formValidity variable to true and call all the functions we wish to perform validation on. Finally, we use another if/else statement to check if our formValidity variable remains true after iterating thru any function calls, and if so hides our top-level error message, and allows the submit event to continue executing. If our variable has acquired a falsy value, we show our top-level error message, and scroll the user to the top of the page.


Note for convivence sake our working example below will not include this scroll feature.

/* validate form */
function validateForm(evt) {
	if (evt.preventDefault) {
	evt.preventDefault(); // prevent form from submitting
	}
	else {
	evt.returnValue = false; // prevent form from submitting in IE8 8
	}
	formValidity = true; // reset value for revalidation
	// add calls below to validation functions
	if (formValidity === true) {
	document.getElementById("errorText").innerHTML = "";
	document.getElementById("errorText").style.display = "none";
	document.getElementsByTagName("form")[0].submit();
	}
else {
document.getElementById("errorText").innerHTML = "Please fix the indicated problems and then resubmit your form.";
document.getElementById("errorText").style.display = "block";
scroll(0,0);
	}
}

Above our validateForm(evt) function, we can finally add a function to validate all text input boxes. The first few lines of this function simple gathers all the necessary elements and appends them to variables. We then reset any error styles from a previous submission fail and incorporate the bulk of our validation in a try statement. Which allows you to define a block of code to be tested for errors while it is being executed.


We’ve included several if and else/if statements that check the value of our input variables for a falsey value, and if so uses the not operator to turn its value truthy, thus executing the code it contains. Our throw statement lets us create custom errors messages. The catch statement then allows us to handle any error that has occurred, and use a parameter name to apply to our throw statement. Which we can then add as the .innerHTML of an element to display to the user. More importantly because an error did occur, we change our formValidity variable within the catch statement to contain a falsy value.


/* validate Personal Info */
function validatePersonalInfo() {
var errorDiv = document.querySelectorAll("div.errorMessage");
var nameField = document.getElementById("field1");
var emailField = document.getElementById("field2");
try {
// reset styles to valid state
nameField.style.background = "";
emailField.style.background = "";
errorDiv[0].style.display = "none";
	if (!(nameField.value || emailField.value)) {
	nameField.style.background = "rgb(255,233,233)";
	emailField.style.background = "rgb(255,233,233)";
	throw "Please fill out all Personal Info fields";
	}
	else if (!(emailField.value)) {
	emailField.style.background = "rgb(255,233,233)";
	throw "Please Enter Your Email address";
	}
	else if (!(nameField.value)) {
	nameField.style.background = "rgb(255,233,233)";
	throw "Please Enter Your Name";}
	}
catch(msg) {
	errorDiv[0].style.display = "block";
	errorDiv[0].innerHTML = msg;
	formValidity = false;}
}

Last but not least we’ll call this function in our validateForm(evt) function below the “add calls below to validation functions” JavaScript comment.


// add calls below to validation functions
validatePersonalInfo();

To see our JavaScript Program in action, test the simple form inputs below.


Note that upon form validation you will automatically be redirected to the next tutorial.


Contact Us

Personal Info