zagoor
zagoor

Reputation: 107

How to block typing "e" and "-" characters in React Hook Form input?

I'm trying to set up a phone number input in react-hook-form library. I set input type to number, but it still accepts "e" and "-" chars. I tried to prevent it like this:

<Controller
  name="phone"
  control={control}
  rules={{ required: true }}
  render={({ onChange, value, ref }) => (
    <Input
      ref={ref}
      type="number"
      label="phone"
      onChange={(e) =>
        /[^e]/.test(e.target.value) && onChange(e.target.value)
      }
      val={value}
    />

But it doesn't work properly. Any recommendations how to solve this problem?

Upvotes: 5

Views: 8914

Answers (1)

NearHuscarl
NearHuscarl

Reputation: 81310

If you want to prevent certain keys from being pressed, you can surpress the keydown event after the check is failed:

<Input
  onKeyPress={(e) => {
    if (e.key === "e" || e.key === "-") {
      e.preventDefault();
    }
  }}
/>

But if you allow all keys but validate it after being pressed, you can use the pattern option like this:

<Controller
  name="phone"
  control={control}
  rules={{ required: true, pattern: /^\d+$/ }}
  render={(props) => {
    const { onChange, value, ref } = props.field; // v7. use props if you're using v6
    const { error } = props.meta;

    return (
      <Input
        ref={ref}
        type="number"
        label="phone"
        onChange={onChange}
        val={value}
      />
    );
  }}
/>

Upvotes: 7

Related Questions