Categories:

Form validation using the keyboard events

Using the onkeypress event, we could create on-the-fly form validation. Now that's something CGI most certainly can't do. The idea is to use the onkeypress event handler inside the form field to check, so as the user types, it is being validated concurrently.

Numbers only

Here's an example that limits a form field to contain only numeric input (on the fly, of course!).

<script type="text/javascript">
function numbersonly(e){
	var unicode=e.charCode? e.charCode : e.keyCode
	if (unicode!=8){ //if the key isn't the backspace key (which we should allow)
		if (unicode<48||unicode>57) //if not a number
			return false //disable key press
	}
}
</script>

<form>
<input type="text" size=18 onkeypress="return numbersonly(event)">
</form>

Try typing in stuff other than numbers into the above box- you can't. How does the script work? By checking to see whether the keycode of the key pressed as the user types falls within the range of the number keys (48~57), and if not, returns false, which disables the keypress action. How did I know 48 to 57 represents the keycode of the numeric keys? Well, by using a simple alert(event.keycode) script to map it out (no fancy tricks here). Then, by using the "onkeypress" event handler, along with function numbersonly() inside the textbox to validate, we have one picky box!

Limit number of characters allowed

<script type="text/javascript">

function limitlength(obj, length){
	var maxlength=length
	if (obj.value.length>maxlength)
		obj.value=obj.value.substring(0, maxlength)
}

</script>

Enter text (max length is 20 characters):
<form>
<textarea onkeyup="return limitlength(this, 20)" style="width: 300px; height: 90px"></textarea>
</form>

Enter text (max length is 20 characters):

Short and effective way to limit the amount of text inside form fields!