JavaScript presses Dead key twice, passes input validation allowing only numbers to be entered

100 views Asked by At

Good morning everyone, I have the following function that validates that only numerical characters can be entered in a text input. The problem is that if I press the Dead key twice, 'ยด is entered in the text input.

input_numeric.onkeydown = numericKeyboard;
function numericKeyboard(e) {
  if (e.key != 0 && e.key != 1 && e.key != 2 && e.key != 3 && e.key != 4 && e.key != 5 && e.key != 6 && e.key != 7 && e.key != 8 && e.key != 9) {
    e.preventDefault();
  }
}

Please someone can help me solve my problem.

1

There are 1 answers

1
mplungjan On

Instead of preventing default, just don't allow any of the not allowed input

Using the input event will handle typing and pasting

const input_numeric = document.getElementById("numeric");
const notallowed = /[^0-9\.\-\+]/g // add e if you need exponent
const allow = (e) => {
  const tgt = e.target;
  const text = tgt.value;
  tgt.value = text.replace(notallowed,"");
};
input_numeric.addEventListener("input", allow);
<input type="text" id="numeric" />

or just

<input type="number" /> which however will allow .e for example due to numbers like 2.04e10

If you insist on preventDefault, we can try this. Note that the input event cannot use preventDefault since it triggers after input

const checkInput = (e,pasting) => {
  let text;
  if (pasting) {
    const clipboardData = e.clipboardData || window.clipboardData;
    text = clipboardData.getData('Text');
  } 
  else text = e.key;

  if (/[^0-9]/.test(text)) {
    console.log(`${pasting ? 'Pasting' : 'Input'} is prevented because it contains a non-numeric character.`);
    e.preventDefault();
  }
}; 
const field = document.getElementById('numeric');
field.addEventListener('paste', (e) => checkInput(e,true));
field.addEventListener('keydown', (e) => {
  checkInput(e, false);
});
<input type="text" id="numeric" />