1

I want to allow only numbers and the forward slash character using the pattern attribute in my input field

4 Answers 4

3
  1. You can use this website to get the keyCode: http://keycode.info/
  2. 0-9 keyCodes are '48'-'57'. Forward slash's keyCode is 191.

function validateNumberAndForwardSlash(event) {
    var key = window.event ? event.keyCode : event.which;

  if (event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 191) {
    return true;
  } else {
    return false;
  }
};
<input type="text" onkeypress="return validateNumberAndForwardSlash(event);">

P.S. This is a keyCode summary article: https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Sign up to request clarification or add additional context in comments.

2 Comments

keypress, e.keyCode and e.which are all deprecated. keydown and e.key or e.code should be used instead.
Also, you might want to take a look at keyjs.dev which shows a bit more information about the different KeyboardEvents if you expand it. 🙂
3
function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode !== 47) 
    {
        return false;
    }
    return true;
}

Comments

2

You should not listen for keyboard events (keydown / keypress / keyup) to filter out certain characters, as the value of the input can also be updated by pasting or dropping text into it and there are many exceptions you should not prevent, such as arrows, delete, escape, shortcuts such as select all, copy, paste... so trying to come up with an exhaustive list of the ones that should be allowed is probably not a good idea.

Instead, just listen for the input event and update the input value removing all invalid characters while preserving the cursor's position:

const input = document.getElementById('input');

input.oninput = (e) => {  
  const cursorPosition = input.selectionStart - 1;
  const hasInvalidCharacters = input.value.match(/[^0-9/]/);

  if (!hasInvalidCharacters) return;
  
  // Replace all non-digits:
  input.value = input.value.replace(/[^0-9/]/g, '');
  
  // Keep cursor position:
  input.setSelectionRange(cursorPosition, cursorPosition);
};
<input id="input" type="text" placeholder="Digits and forward slash only" />

Here you can see a similar answer and example for a slightly more complex behaviour to allow only numbers with one single decimal separator: https://stackoverflow.com/a/64084513/3723993

Comments

1

If someone is nowadays looking for the answer (like I was), the simplest and obvious one is (at least from today's perspective) missing. Additionally, I think this is also the one which was actually asked for. Namely, the use of the pattern attribute of the HTML input field.

To allow only digits and slashes as requested, an input field with the following pattern can be used:

<input type="text" pattern="[0-9/]*" title="Please enter only numbers or slashes!">

The title is displayed in many browsers as a hint to the user if his input does not match the pattern. If the input of at least one character is required, the pattern "[0-9/]+" can be used instead (and the input field should be set to be required).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.