Reputation: 11059
I am using
document.getElementById('input-field').addEventListener('keyup', function (e) {
if (!String.fromCharCode(e.which).match(/[A-Za-z0-9,]/)) {
event.preventDefault();
}
});
It almost works. The problem is that I cannot use key arrows, backspace, delete, ctrl+a, etc.
How can I limit it to only those keys that will give a string representation in the specific input?
Upvotes: 2
Views: 3791
Reputation: 9810
Well there is somehow to limit your input range. But I think in this case you are looking for a way to identify only printable key events.
You can achieve this by using the solution proposed by @TimDown on How to detect if the pressed key will produce a character inside an <input>
text-box? applied to a keypress
event as you can see on the code below. So then, you can work just with printable key events.
function isCharacterKeyPress(evt) {
if (typeof evt.which == "undefined") {
// This is IE, which only fires keypress events for printable keys
return true;
} else if (typeof evt.which == "number" && evt.which > 0) {
// In other browsers except old versions of WebKit, evt.which is
// only greater than zero if the keypress is a printable key.
// We need to filter out backspace and ctrl/alt/meta key combinations
return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
}
return false;
}
document.getElementById('input-field').addEventListener('keypress', function (e) {
if(isCharacterKeyPress(e)){
if (!String.fromCharCode(e.which).match(/[A-Za-z0-9,]/)) {
e.preventDefault();
}
}
});
<input type="text" id="input-field" placeholder="input text here">
Upvotes: 0
Reputation: 32165
To ignore those keys you need to add a condition before validating your input.
For example you can make an array containing the list of all KeyCodes that you want to ignore and just test if the typed key isn't one of them.
Here's what you need:
document.getElementById('input-field').addEventListener('keypress', function(e) {
//An array of special Keys
var specialKeys = [37, 38, 39, 40, 8, 13, 27, 46];
if (specialKeys.indexOf(e.which) === -1) {
console.log(String.fromCharCode(e.which)+ ' Key is validated!');
if (!String.fromCharCode(e.which).match(/[A-Za-z0-9,]/)) {
event.preventDefault();
}
}
});
<input type="text" id="input-field" placeholder="input text here">
Note:
As mentioned in comments you need to use keypress
event instead of keyup
to validate every inputted character immediately.
Upvotes: 1