Reputation: 582
Does anyone have a working dynamic javascript input filter that limits text inputs across multiple browsers?
I've seen multiple examples online, but most of them seem to have flaws or lack multibrowser support.
My current attempt is posted below, but it's failing for shifted numbers under firefox, and I haven't tried other browsers yet.
As http://www.quirksmode.org/js/keys.html shows, it's not an easy problem.
Does anyone have a better solution?
var numb = /[0-9]/;
var lwr = /[a-z]/;
var upr = /[A-Z]/;
var alpha = /a-zA-Z]/; //not checked
var alphaNum = /a-zA-Z0-9/; //not checked
function onKeyPressAcceptValues(e, reg){
var key = window.event ? e.keyCode : e.which;
//permit backspace, tab, delete, arrow buttons, (key == 0 for arrow keys)
alert(key);
if(key == 8 || key == 9 || key == 46 ||(key>32 && key <41 ||key == 0)){
return true;
}
var keychar = String.fromCharCode(key);
return reg.test(keychar);
}
function isNumberKey(parm) {return onKeyPressAcceptValues(parm,numb);}
function isLowerKey(parm) {return onKeyPressAcceptValues(parm,lwr);}
function isUpperKey(parm) {return onKeyPressAcceptValues(parm,upr);}
function isAlphaKey(parm) {return onKeyPressAcceptValues(parm,alpha);}
function isAlphanumKey(parm) {return onKeyPressAcceptValues(parm,alphaNum);}
It would be used via
<input type="text" name="pw[first_name]" size="15" maxlength="15" onkeypress="return isAlphaKey(event)">
Upvotes: 9
Views: 9181
Reputation: 11167
Would checking and removing invalid values after input work?
Checking the charCode and keyCode can get to be quite difficult across browser why not check the value that is actually added to the text field?
Invert your regular expressions and they match everything you don't want. Once you have that just use your inverted regular expression to replace data inserted into your input boxes that you don't want.
A quick example I created at http://jsbin.com/ulibu has a text box that ONLY accepts integers. It has a small javascript block which strips non-digits from the field:
function checktext( e ) {
//Remove digits
//Yes, the global search/replace is important. If we don't use a global
//replace ctrl+v will remove only the first invalid character instead of
//them.
e.value = e.value.replace( /[^\d]/g , '' );
}
And the input box is declared with a keyup event to catch anything typed:
<input type="text" id="text" onkeyup="checktext(this);"/>
This sure isn't perfect. Things you'll still need to do:
Upvotes: 2
Reputation: 114367
Here's one way to do it:
The user thinks they're typing into the field, but they're not.
Upvotes: -1
Reputation: 82483
Trapping keyboard events won't do the trick anyways because the user can always use Edit | Paste. Even if you do come up with a cross-browser solution to handle that, the user can always bypass everything by disabling Javascript.
In other words, don't waste your time. Just give the user an error when they attempt to submit invalid data.
Upvotes: 2