React-hook-form and react-phone-input-2 throws TypeError: elm.focus is not a function

509 Views Asked by At

The following code throws an error "TypeError: elm.focus is not a function" when submitting the form. The issue started appearing after pattern validation was added. Basically, I'd like to ensure that both "require" and "phone validity/pattern" are checked before submitting the form.

 <Controller
    name="phone1"
    control={control}
    rules={{
      required: "Phone is required",
      pattern: /^\+380\s\(\d{2}\)\s\d{3}\s\d{2}\s\d{2}$/,
    }}
    render={({ field }) => (
      <>
        <PhoneInput
          {...field}
          country={"ua"}
          onlyCountries={["ua"]}
          onChange={(value, country, e, formattedValue) => {
            field.onChange(formattedValue);
          }}
          inputProps={{
            autoFocus: false,
            countryCodeEditable: false,
          }}
        />
        {errors.phone1 && <p role="alert">{errors.phone1.message}</p>}
      </>
    )}
  />
1

There are 1 best solutions below

0
Paul S. On

In field prop of render function has a ref prop needed for input to work properly. PhoneInput this ref prop need to be moved to inputProps

render={({field: {name, value, onChange, ref, onBlur}}) =>
    <PhoneInput
        value={value}
        onChange={(value, country, event, formattedValue) => {
            onChange(formattedValue);
        }}
        onBlur={onBlur}
        inputProps={{
            autoFocus: false,
            countryCodeEditable: false,
            name,
            ref
        }}
    />
}