I took some time to create a function, which can validate which keys you input on an element. So far it has two uses:
- You call
.validate()
on the object, but make sure it has adata-match
attribute with the regex in it - You call
.validate("REGEX")
on the object, but replaceREGEX
with your actual regular expression
Here is an example:
document.getElementById("input").validate("[0-9A-Fa-f]");
This will only allow characters 0-9, A-F, and a-f. Nothing else.
I want to know, if I can improve this code. So far I have it the way I want it to be, but I would surely love someone else's feedback on it as well. It is really light-weight and can easily be implemented.
Thanks a lot!
Object.prototype.validate = function(myRegex) {
var regex = this.getAttribute("data-match") || myRegex;
var allowed = [8, 37, 38, 39, 40, 46];
this.addEventListener("keydown", function(e) {
var c = (e.metaKey ? '⌘-' : '') + String.fromCharCode(e.keyCode);
if (!e.shiftKey && !e.metaKey) c = c.toLowerCase();
if ((e.ctrlKey && (e.keyCode == 65 || e.keyCode == 97)) || c == '⌘-A') return true;
if (c.match(regex) || allowed.indexOf(e.which) >= 0) {
//Do nothing
} else {
e.preventDefault();
}
});
}
document.getElementById("input").validate("[0-9A-Fa-f]");
<input type="text" id="input" />