Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JavaScript verify text inputs as the user types
// used to verify characters and prevent incorrect input as the user is typing.
// TODO: detect special characters like period/comma/?/etc. in the first regexp
// USAGE: use the keydown event: "return dynamicVerify(e, '[0-9a-zA-Z]');"
// e = event, re = regexp for allowed characters, ce = regexp for allowed key codes
function dynamicVerify(e, re, ke) {
var key = e.keyCode || e.which;
var keychar = String.fromCharCode(key);
var rexp = new RegExp(re);
var kexp = new RegExp(ke);
// differentiate lower/upper case
if (!e.shiftKey) {
keychar = keychar.toLowerCase();
}
// allow capital letters if they match rexp
if (e.shiftKey && rexp.test(keychar) === true && key >= 65 && key <= 90) {
return true;
}
// otherwise only allow shift tab
else if (e.shiftKey && key != 9) {
return false;
}
// allow specific key codes using kexp
if (ke && ke != '') {
if (kexp.test(key) === true) {
return true;
}
}
// ctrl/command-a/x/c/v (select all/cut/copy/paste)
if ((e.ctrlKey || e.metaKey) && (key == 65 || key == 88 || key == 67 || key == 86)) {
return true;
}
// allow backspace, left/right arrow, etc.
if (key < 48 || (key > 90 && key < 186)) {
return true;
}
// allow specific characters using regexp
if (rexp.test(keychar) === true) {
return true;
}
// no matches
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.