React hook form - form is completely optional or completely mandatory (if any of the field is filled). Please help the optimized way. Thanks.
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>
);