Jamgreen Jamgreen - 1 month ago 7
HTML Question

Validate key input in field with javascript

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?

Answer

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 keypressevent instead of keyup to validate every inputted character immediately.

Comments