Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

557
Views
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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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="" />

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!