Filtered keystrokes with JavaScript

This small set of scripts should give you a starting point for filtering the valid input to certain form fields to ensure that you shouldn’t end up with input that you don’t want*.

Basically you’d have the following javascript functions defined:

function isNumber( evt ) {
	valid		= true;
	if( evt.which || ( evt.which != 0 && evt.charCode != 0 ) ) {
		var charCode	= ( evt.which ) ? evt.which : event.keyCode;
		if( charCode > 31 && ( charCode < 48 || charCode > 57 ) ) {
			valid	= false;
		}
	}
	return valid;
}

function isValidEmailCharacter( evt ) {
	valid	= true;
	if( evt.which == null || ( evt.which != 0 && evt.charCode != 0 ) ) {
		var charCode	= ( evt.which ) ? evt.which : event.keyCode;
		var char		= String.fromCharCode( charCode );
		var re			= new RegExp( /([0-9A-Za-z-_@.])/ );
		valid			= re.test( char );
	}
	return valid;
}

function isValidPhoneCharacter( evt ) {
	valid	= true;
	if( evt.which == null || ( evt.which != 0 && evt.charCode != 0 ) ) {
		var charCode	= ( evt.which ) ? evt.which : event.keyCode;
		var char		= String.fromCharCode( charCode );
		var re			= new RegExp( /([0-9+\s\[\]])/ );
		valid			= re.test( char );
	}
	return valid;
}

Then we add an onkeypress event to the relevant form fields to filter out any of the keystrokes you don’t want. This would look something like:

<input
	type="text" name="num"
	onkeypress="return isNumber( event );"
/>
<input
	type="text" name="year" maxlength="4"
	onkeypress="return isNumber( event );"
/>
<input
	type="text" name="email"
	onkeypress="return isValidEmailCharacter( event );"
/>
<input type="text" name="phone" onkeypress="return isValidPhoneCharacter( event );" />

The only problem with this method of filtering input to the form elements is that key combos using filtered characters will not work, i.e. ⌘+A to select the entire entry in a text field will not work when we’re applying the isNumber filter to that field. The solution would be to create a list of key combonations that are allowed.

Not a necessity, but it can’t hurt.
- Chris

* That’s not to say you shouldn’t validate the form when it’s submitted, the non-JavaScript action will be to allow anything.