DEV Community

Cover image for maxLength input type=number
Matheus Vieira do Nascimento
Matheus Vieira do Nascimento

Posted on

maxLength input type=number

Have you ever needed to use a numeric input but couldn't limit the maximum number of characters?! I faced this recently and I'm sharing what helped me!

๐Ÿ” Developing a Custom OTP Input Component ๐Ÿ”
Recently, I needed to create an OTP input component for a project where users had to enter a verification code sent via SMS or email. The challenge was to ensure that the input accepted only numbers and that each field allowed only a single digit.

Problem
The <input type="number"/> ignores the HTML "maxLength" property, making it necessary to use JavaScript to achieve this behavior. When we create an input of this type, the element automatically converts all non-numeric values into empty strings! After some research and experimentation, I came up with a solution that combines simplicity and efficiency.

๐Ÿ“‹Input code:



<input
  type="number"
  maxLength={1}
  inputMode="numeric" //Opens numeric keyboard on mobile
  onInput={(e) => {
    const target = e.target as HTMLInputElement;

    // Removes non-numeric characters
    target.value = target.value.replace(/\D/g, "");

    // Limits to one digit
    if (target.value.length > target.maxLength) {
      target.value = target.value.slice(0, target.maxLength);
    }
  }}
/>


Enter fullscreen mode Exit fullscreen mode

๐Ÿ’กHow it works:

  • replace(/\D/g, ""): Removes any non-numeric characters, ensuring that only numbers are entered.

  • maxLength={1} e slice(0, target.maxLength): Limit the input to a single digit.

This solution was essential to create a clean and intuitive user experience, focusing on simplicity and efficiency in entering the OTP code.

But why handle non-numeric characters if the input type is number?
Surprisingly, the letter "e" is interpreted as a number, meaning if the user somehow entered "e", it would be accepted. So, even with type=number, it was necessary to add this regex.

๐Ÿ˜Š BONUS
If you've ever used a numeric input, you've probably encountered those annoying little arrows:

Image description

Here's the CSS to hide them:



input {
  &::-webkit-outer-spin-button,
  &::-webkit-inner-spin-button {
      -webkit-appearance: none;
      margin: 0;
  }
  -moz-appearance: textfield;
}


Enter fullscreen mode Exit fullscreen mode

I'm always looking for new ways to optimize the user experience in a simple yet effective way. What do you think of this approach? Any suggestions or alternatives that you've used? Let's discuss! ๐Ÿ’ฌ

Top comments (0)