Input control in text fields

September 20, 2006

One of the projects I'm working on right now involves a lot of form input. So I have come up with a small script to control what a user can write in a text/textarea field.
It allows us to control what characters the user is allowed to enter.
Here's an example:
Only alphas:

Only numerics:

Download and embed

To use inputControl you simply download it (1 kB) and embed it in the head section of your web pages:
<script type="text/javascript" src="inputControl.js"></script>

Throw in a form or two

You need one or more forms on your page to try it out with. The html code for the form in the example above is:
<form  name="myForm" >
Only alphas: [[[br/]]]<input type="text" name="alphas">[[[br/]]]
Only numerics:[[[br/]]]<input type="text" name="numerics">

Add input rules

To add input rules for a form and its elements you use the method
where formName i s the name of your form and ruleObj is an object where each member has the name of an input element (text or textfield) and a string value corresponding to a regular expression.
		"alphas"  :  "[a-zA-Z����]",
		"numerics"   :  "[0-9\.]"

So in the example above what we say is: In the form myForm the input field named alphas should only accept the characters a-z, A-Z, �, �, � and �. The input field named numerics should only accept 0-9 and period.
If you need to read up a bit on regular expressions I recommend this article.

Usability considerations

This type of input control sends a clear signal to the user what type of input is allowed and not allowed in a specific field.
But it also demands that you think through your design thoroughly -- for example users won't be happy if they have uncommon characters in their names that they can't input.
And what about those (not too uncommon) users that don't type and look at the screen at the same time -- they might get a surprise when they look up. One of my colleagues suggested a small sound indication -- a"beep" or something -- to indicate that a character is not allowed. This might be a feasible solution -- feel welcome to modify my script. An idea would be to use Scott Schiller's excellent Sound Manager.
Finally I would like to mention that the script modifies the onkeypress events of the specified fields and that I was inspired by this script when writing inputControl.