Solid Basic Javascript Input Validation

Here is a simple yet pretty powerful and easy to use way to do validation on HTML form text boxes and text areas and similar controls. It checks to make sure required form field have *something* in them before allowing processing to continue. It’s a good simple way to add some basic validation to prevent trusted individuals from forgetting to fill out required fields. This is generally useful for internal websites where you can assume the user isn’t trying to hack the site.

First we have two global JS variables that define the default and error-ed state of text boxes in question. Below I have standard controls with black borders and error-ed controls with red borders.

//assign a default border color for all form controls
var defaultControlBorderColor = '#000000'; 

//use a special color to highlight trouble (such as if a control doesn't validate)
var notificationControlBorderColor = '#ff0000'; 

Below I have the primary function that does the field validation. From the code you can see that it loops through a list of form control IDs delimited by the ‘|’ pipe character. If at least one control is empty, the function will return false and highlight all fields that still require user input. It also attempt to focus on one of those fields with the cursor.

// takes a list of text and or textarea controls and makes sure they have values in them
function validateForm(delimitedFieldIdsRequired)
{
	var functionSuccess = true;
	var requiredFields = delimitedFieldIdsRequired.split('|');
	
	//go through each item in the list of fields that need to be checked
	for(var i = 0; i < requiredFields.length; i++)
	{
		//get the actual object from the id name
		var field = document.getElementById(requiredFields[i]);
		
		//make sure the field is not null or empty
		if (field.value == null || trimString(field.value) == '')
		{
			//highlight the control bright red, so the user knows they need to fill it in
			field.style.border = '3px solid ' + notificationControlBorderColor;
			field.focus();
			functionSuccess = false;
		}
		else
		{
			//this item may have been defined as not filled in in a previous attempt,
			//if it is ok now, make sure the border is set back to normal
			field.style.border = '1px solid ' + defaultControlBorderColor;
		}
	}
	
	return functionSuccess;
}

To make your check, use something like the code below. See how the function is called with field IDs split up by the ‘|’ pipe character. Once all of the form fields are checked out as ok, the processing will continue.

var formValidationResult;

formValidationResult = validateForm('fielditem1|fielditem2|fielditem3');

//see if the form data is at least not empty
if(formValidationResult == true)
{
  //success, so continue processing...
}

Easy and effective for my needs.

This entry was posted in General and tagged , , , , , , , . Bookmark the permalink.