最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex to allow only numbers and max 2 digits - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Aug 2, 2021 at 20:46 RRPRRP 2,8539 gold badges32 silver badges55 bronze badges 4
  • 1 Because the input is a single char. – Wiktor Stribiżew Commented Aug 2, 2021 at 20:49
  • 2 How about <input type="number" min="0" max="99"> ? – Robo Robok Commented Aug 2, 2021 at 20:49
  • type=number wont work in firefox, also with that the user can still type in more digits than 2 – RRP Commented Aug 2, 2021 at 20:50
  • If you have a strict requirement on the number length you should not forget to check it on server side, both input field and JavaScript can be bypassed by the user. – Robert Commented Aug 2, 2021 at 20:55
Add a ment  | 

3 Answers 3

Reset to default 4

I would remend 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 bined 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="" />

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 mon 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.

You Must use event value, and I reend 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);
}
发布评论

评论列表(0)

  1. 暂无评论