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

225
Visualizações
React hook form - all fields are mandatory if any of the field is filled else optional

React hook form - form is completely optional or completely mandatory (if any of the field is filled). Please help the optimized way. Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If I understood correctly, you want to submit the form with default/empty values only if none of the fields have been modified, and otherwise all fields need to have filled values?

The simplest approach I believe would be to use the isDirty prop of formState to set the required prop in the register function.

const {
    register,
    handleSubmit,
    formState: { errors, isDirty },
} = useForm();

return (
    <form onSubmit={handleSubmit(() => {})}>
        <TextField
            label={'optional1'}
            error={!!errors.optional1}
            {...register('optional1', { required: isDirty })}
        />
        <TextField
            label={'optional2'}
            error={!!errors.optional2}
            {...register('optional2', { required: isDirty })}
        />
        <Button color="inherit" type="submit">
            Create
        </Button>
    </form>
);

This way however, e.g. text fields remain dirty after emptying some added input. So you would need to add a some form reset functionality such as a reset-button to fix that.

Although, instead of a reset button, I would check that the field values equal default/empty values. Note that the checking will require a bit more code if you have different kinds of fields or different default values. A reset button might be nice in this case also if you have a lot of fields though.

const {
    register,
    handleSubmit,
    getValues,
    formState: { errors },
} = useForm();
const fieldValues = Object.values(getValues());
const someOptionalFilled = fieldValues.some(fieldValue => fieldValue != '')

return (
    <form onSubmit={handleSubmit(() => {})}>
        <TextField
            label={'optional1'}
            error={!!errors.optional1}
            {...register('optional1', { required: someOptionalFilled })}
        />
        <TextField
            label={'optional2'}
            error={!!errors.optional2}
            {...register('optional2', { required: someOptionalFilled })}
        />
        <Button color="inherit" type="submit">
            Create
        </Button>
    </form>
);
about 4 years ago · Juan Pablo Isaza Relatório
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