I want to allow only numbers and the forward slash character using the pattern attribute in my input field
4 Answers
- You can use this website to get the keyCode: http://keycode.info/
- 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
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
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).