2👍
The following snippet will not allow anything to be entered into the input element if the length of the input’s value is already 4, or if a non-numeric character is typed (but will allow ‘Backspace’ and ‘Delete’ keys):
EDIT : Implemented Hiws’ suggestion to let the user type in numbers even if the length is 4, if some text is selected in the input element
function filterKey(e) {
let previousValue = e.target.value;
let key = e.keyCode || e.charCode;
if (key != 8 && key != 46) { // Ignore backspace and delete
if (
// preventDefault if length of input is 4 and no text is selected in the input
( String(e.target.value).length >= 4 && e.target.selectionStart === e.target.selectionEnd ) ||
// preventDefault if entered a space or non-number
!e.key.trim() || isNaN(e.key)
) {
// Prevent input if input length crosses 4,
// or if input is not a number
e.preventDefault();
// Include below line only if you have no other event listeners on the element, or its parents
e.stopImmediatePropagation();
return;
}
}
}
1👍
You block keys other than numbers only if number value already equals to 4
. Try changing your blocking logic to:
if (String(value).length > 4 || !isNaN(Number(key)) || unwanted keyCodes) {
e.preventDefault();
return;
0👍
You can use a regex to test against the value of the input field and avoid messing with keyCodes.
if ( !/^[0-9]{0,4}$/.test(String(value)) ) {
e.preventDefault();
return;
}
Source:stackexchange.com