Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

273
Visualizações
One input field, different name and validation react hook form

I have a form created with React hook form and input field thant can have 2 different values: a pec email or a SDI code with different validation.

I get error with validation: keep telling me that sdi should be 7 characters but the name is set to "pecEmail". Also at page load "name" is set to "sdiCode" but if an email is already there, should be "email". It changes when I click the input. I tried to pass the name field in register but I lost all the validation

ref={register(isPec ? 'pecEmail' : 'sdiCode', {

code here:

const [isPec, setIsPec] = useState()
const sdiOrPec = watch(['sdiCode', 'pecEmail'])

  useEffect(() => {
    setIsPec(
      (sdiOrPec.sdiCode && sdiOrPec.sdiCode.includes('@')) ||
        (sdiOrPec.pecEmail && sdiOrPec.pecEmail.includes('@'))
    )
  }, [watch])


  
            <div className='input-container'>
              <div
                className={`input-container__item ${
                  errors[isPec ? 'pecEmail' : 'sdiCode'] && 'has-error'
                }`}
              >
                <label>{t('components.BillingInfoForm.sdiLabel')}</label>
                <input
                  type='text'
                  name={!isPec ? 'sdiCode' : 'pecEmail'}
                  defaultValue={
                    get(billingInformations, 'sdiCode')
                      ? get(billingInformations, 'sdiCode')
                      : get(billingInformations, 'pecEmail')
                      ? get(billingInformations, 'pecEmail')
                      : ''
                  }
                  placeholder={t('components.BillingInfoForm.sdiPlaceholder')}
                  ref={register({
                    maxLength: {
                      value: isPec ? 320 : 7,
                      message:
                        !isPec &&
                        t('components.BillingInfoForm.sdiMessageError'),
                    },
                    minLength: {
                      value: isPec ? 3 : 7,
                      message:
                        !isPec &&
                        t('components.BillingInfoForm.sdiMessageError'),
                    },
                    validate: {
                      value: (value) => {
                        if (isPec && sdiOrPec.pecEmail) {
                          return (
                            isEmailValid(sdiOrPec.pecEmail) ||
                            t('components.SignupForm.emailError')
                          )
                        }
                      },
                    },
                  })}
                />
                  {errors[isPec ? 'pecEmail' : 'sdiCode'] && (
                  <small>
                    {errors[isPec ? 'pecEmail' : 'sdiCode'].message}
                  </small>
                )}
              </div>
            </div>
          

Thanks

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda