Form field does not focus on not stating data or contain invalid information. React-Hooks-Forms w/ Imask

Asked

Viewed 23 times

0

I have a form for entering data such as credit card, as can be seen below:

React.useEffect(() => {
    register({ name: 'cardNumber' }, { required: true, validate: isValidCardNumber })
    register({ name: 'securityCode' }, { required: true, validate: isValidSecurityCode })
    register({ name: 'expirationMonth' }, { required: true, validate: isValidExpireDate })
    register(
      { name: 'expirationYear' },
      { required: true, minLength: 4, validate: (value) => value >= new Date().getFullYear() }
    )

    return () => {
      unregister('cardNumber')
      unregister('securityCode')
      unregister('expirationMonth')
      unregister('expirationYear')
    }
  }, [checkout])

  const { getInputProps: getInputPropsCardNumber } = useImask({
    mask: masks.CARD_NUMBER_MASK,
    lazy: true,
    unmask: true,
    value: watch('cardNumber'),
    onAccept: (value) => setValue('cardNumber', value),
  })

But when this field in Forms is empty or invalid, instead of it bringing Focus to the field where this information is missing it does nothing, because the form does not have the ref to give the Focus as in the example below:

SEAL

<div className="font-bold text-sm leading-base text-dark mb-2">NOME NO CARTÃO</div>
    <Field
    ref={register({ required: true })}
    name="holderName"
    label="Exemplo Silva"
    hasError={!!errors?.holderName}
    />

NO SEAL

<div className="font-bold text-sm leading-base text-dark mb-2">NÚMERO DO CARTÃO</div>
    <Field
    {...getInputPropsCardNumber()}
    name="cardNumber"
    label="1234 5678 9012 3456"
    hasError={!!errors?.cardNumber}
    />

I would have to do this Focus manually once Forms rejected the data and did not get lost in the ref.

  • he already does it, strange his doubt

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.