RRP
RRP

Reputation: 2853

Regex to allow only numbers and max 2 digits

I am working on an input field, that should allow users to enter numbers from 0 to 99. In addition the user should not be allowed to type in a 3rd digit.

To tackle the above i have the following regex /^([0-9]{2})$/

I have the following function that is triggered on keypress event

    onlyAllowNumbers(evnt: KeyboardEvent): boolean {
        const charCode = evnt.key;
        const pattern = /^([0-9]{2})$/;

        return pattern.test(charCode);
}

The above pattern isn't allowing me to enter in any numbers in the input field.

Upvotes: 2

Views: 19715

Answers (3)

Andrei
Andrei

Reputation: 1863

Presumably you will want to use this in a form. If you're targeting modern browsers, the input field supports the pattern attribute which adds an extra layer of pattern enforcement (in case JavaScript is disabled).

If you're considering the best user experience, you'll also want to anticipate less common use cases. For example: if the user selects one of the digits and types another one, they are indicating they are replacing the selected digit with the new one.

The following code takes all of this into consideration:

<form>
  <input id="only_max_two_digits" type="text" pattern="^\d{1,2}$" />
  <input type="submit" />
</form>

<script type="text/javascript">
  function remove_substr(s, src, dst) {
    return s.substr(0, src) + s.substr(dst);
  }

  document
    .querySelector("#only_max_two_digits")
    .addEventListener("keypress", (e) => {
      const { value, pattern, selectionStart, selectionEnd } = e.target;
      const next = remove_substr(value, selectionStart, selectionEnd) + e.key;

      if (!new RegExp(pattern).test(next)) {
        e.preventDefault();
      }
    });
</script>

The function remove_substr removes a substring from a string between two given numerical bounds. In this case, we're using it to remove the selected text, because we know where the selection begins and ends.

The event listener:

  • It is triggered by the keypress event, meaning when the key is down, but the <input>'s value has not yet updated.
  • The next variable contains the estimation of what the next value will be, by 1) removing the currently selected text (if any) and appending the value of the key that is being pressed.
  • If the value of the next variable doesn't pass the Regex pattern test, <input> is prevented from updating.

Here's a working CodeSandbox example.

Upvotes: 1

Vitalii
Vitalii

Reputation: 2131

I would recommend to update regex to allow 0 or 2 digits- /^[0-9]{0,2}$/.

The following values will match: '', '0', '1', ... '10', ... '99'.

keypress event has the following fields:

  • event.target.value - value of input before new key was pressed
  • event.key - string value of the key that was pressed

When event.target.value and event.key are combined together we can estimate new value of the input.

event.preventDefault() call can be used to block keypress event if the resulting value does not match the needed pattern.

document.getElementById('myinput').addEventListener('keypress', event => {
    if (!`${event.target.value}${event.key}`.match(/^[0-9]{0,2}$/)) {
        // block the input if result does not match
        event.preventDefault();
        event.stopPropagation();
        return false;
    }
});
<input id="myinput" type="text" value="" />

Upvotes: 4

Edwin Felipe
Edwin Felipe

Reputation: 21

You Must use event value, and I recomend use the regex here in code, the event key for numbers never match the regex cause '1' is only one digit

//evnt.key will return you the key pressed value

onlyAllowNumbers(evnt: KeyboardEvent): boolean {
        const value = evnt.target.value;
        const pattern = /^\d{2}$/;

        return pattern.test(value);
}

Upvotes: 0

Related Questions