On-the-fly Form Validation with JavaScript Regular Expressions

November 19th, 2007 by Brian Leave a reply »

I needed to check a text input field on a form to allow only specific values as the user typed in the field. The regular expression only allows characters a-z, numbers 0-9, the “dash” symbol and the underscore. Not sure why, but I had to break out the check for a space into a second regex.

Here's the JavaScript function:
<script language="javascript" type="text/javascript">
function testField(oField) {

	var illegalChars = /[^a-zA-Z0-9_-]/;
	var spaceChars = /\s/;
		// allow only letters, numbers, dashes and underscores
	if (illegalChars.test(oPrefix.value) || spaceChars.test(oPrefix.value)) {
		alert("The prefix may only contain letters, numbers, dashes and underscores.");
		oPrefix.value = oPrefix.value.substring(0,oPrefix.value.length-1).toUpperCase();
	}
	else {
		oPrefix.value = oPrefix.value.toUpperCase();
	}

}
</script>

And here's the HTML form that calls the script through the "onKeyUp" action.

<form name='frmTest' method="POST" action="somepage.php">
Text: <input type='text' name='someFieldName' value='' maxlength="5" style="width:65px;"  onkeyup="testField(this)">
</form>
Advertisement

1 comment

  1. This function seems to me quite useful und could be a good start to write a common On-the-fly-Validation-Script. I am searching for a JavaScript that provides On-the-fly-Validation of form fields, but I haven’t found any scripts up to now. Frameworks like Zend are a bit limited, they just allow to validate fields after form submitting.

Leave a Reply