1fb69f117379804f644a
·2 min read

How to Prevent Users from Entering Non-Numeric Characters in Input Fields

html
javascript
4d5fd787ac74e0caa4f7

Sohan R. Emon

Developer, Learner, Tech Enthusiast

Converting a Text Input Field into a Number-Only Input Field

One common use case in web development is allowing users to input a numerical value into a text input field. While this can be done with a standard text input field, it can be useful to convert the input field into a number-only input field to prevent users from entering non-numeric characters.

To achieve this, we can use the onChange event handler on the input field to validate user input and only allow digits. Here's an example:

html
<input
  type="text"
  onChange={(e) => {
    const char = e.target.value.at(-1) || '';
    if (/\d/.test(char)) {
      e.target.size = e.target.value.length;
    } else {
      e.target.value = e.target.value.slice(0, -1);
    }
  }}
/>

In this example, we're using a regular expression (/\d/) to check if the last character entered by the user is a digit. If it is, we update the input field's size attribute to match the length of the input value. If it's not, we remove the last character from the input value.

Controlling the Size of the Input Field

Using the size attribute instead of min-width to control the size of the input field has a few advantages. First, the size attribute is designed specifically for controlling the width of input fields, while min-width is a more general CSS property that can be used for a variety of elements.

Second, the size attribute is relative to the font size of the input field, while min-width is an absolute value. This means that if the user changes the font size of their browser, the size attribute will adjust accordingly, while min-width will remain constant.

Why Using size Instead of min-width

Using the size attribute instead of min-width to control the size of the input field can provide control over input field width. Input field does not abide min-width.

React Hook Form

Thankfully, React Hook Form makes this process seamless. Here's an example of how to handle a form field with specific input requirements using react-hook-form and shadcn/ui.

tsx
<FormField
        name={'fieldName'}
        control={control}
        render={({ field }) => (
          <FormItem>
            <Input
              maxLength={2} // Restrict input length to 2 characters
              {...field}
              onChange={(e) =>
                field.onChange(e.target.value.replace(/\D/g, '')) // Remove non-numeric characters
              }
            />
            <FormMessage />
          </FormItem>
        )}
      />

Found this useful?