JavaScript Input Validation
Thu Feb 28, 2008 · 175 words

What could be a better “comeback” subject than one of the lamest and most boring of all time - how to validate form input in JavaScript. Everyone and their dog has their way, here's mine, which I think is quite flexible and reusable.

We typically need 3 things for validation - the names of fields to check, some checking criteria and a more user-friendly message to report to the user in case of an error. This Prototype-using function does that. The fields object could of course be moved outside the function and used as a parameter.

function validateForm ()
{
	var fields = [
		{field: 'user-email', name: 'your email', match: '^[A-Z0-9._]+@[A-Z0-9.-]+.[A-Z]{2,4}$'},
		{field: 'album-year', name: 'release year', match: '\{4}d+'},
		{field: 'artist-description', name: 'artist info', match: '\w+'}
	];

	for (i = 0; i < fields.length; i++)
	{
		var e = fields[i];
		if (!new RegExp (e.match).test ($F(e.field)))
		{
			alert ('Error - please check ' + e.name + '!');
			return false;
		}
	}
	return true;
}

Just attach return validateForm() to the onsubmit to your form and that's it.


back · essays · credits ·