
JavaScript to limit form field input text to specific characters
The first field will only accept characters I have identified as appropriate for a person's name (alphabetical, space, hyphen, apostrophe, and period).
The second field will only accept letters.
The third field will only accept numbers.
The fourth field will only accept "name characters" and "numbers".
As you press down on each key on your keyboard, the keystroke is intercepted and only allows the value to be "accepted" if it matches the required criteria.
Here is what the form looks like - I use the "onkeypress" event to call "inputLimiter" with the name of the type of text I want to limit it to:
<form name="InputLimiter">
<p>Name Characters: <input type="text" id="NameCharacters" onkeypress="return inputLimiter(event,'NameCharacters')" value="" /></p>
<p>Letters Only: <input type="text" id="LettersOnly" onkeypress="return inputLimiter(event,'Letters')" value="" /></p>
<p>Numbers Only: <input type="text" id="NumbersOnly" onkeypress="return inputLimiter(event,'Numbers')" value="" /></p>
<p>Letters, Numbers, Hyphens, and Spaces: <input type="text" id="NameCharactersAndNumbers" onkeypress="return inputLimiter(event,'NameCharactersAndNumbers')" value="" /></p>
</form>
Here is the function. Notice that the names of the text-types are very easy to configure - just add a new allow == 'Letters' then type out each fo the characters you want to allow in the AllowableCharacters= section.
function inputLimiter(e,allow) {
var AllowableCharacters = '';
if (allow == 'Letters'){AllowableCharacters=' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';}
if (allow == 'Numbers'){AllowableCharacters='1234567890';}
if (allow == 'NameCharacters'){AllowableCharacters=' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-.\'';}
if (allow == 'NameCharactersAndNumbers'){AllowableCharacters='1234567890 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-\'';}
var k = document.all?parseInt(e.keyCode): parseInt(e.which);
if (k!=13 && k!=8 && k!=0){
if ((e.ctrlKey==false) && (e.altKey==false)) {
return (AllowableCharacters.indexOf(String.fromCharCode(k))!=-1);
} else {
return true;
}
} else {
return true;
}
}