I use react-hook-form in onChange mode. I enable/disable the submit button depending on the validation state. It works just fine.
Now I have to switch to onBlur mode. And the current solution is not working as expected anymore. When all the field became valid I expect the submit button became enabled immediately. Now it only became enabled when I click out of the last field. What should I change in my code to work as expected?
const { register, errors, handleSubmit, formState } = useForm({
mode: "onChange" // I want to change it to onBlur
});
const { isValid } = formState;
...
<input disabled={!isValid} type="submit" />
Here is an example: https://codesandbox.io/s/react-hook-form-disable-submit-button-onblur-0293x?file=/src/index.js
UPDATE WITH SOLUTION: NearHuscarl's answer helped to find the solution. I have to stay at the onChange mode and handle the display of the error message myself. I only displaying the error if the field is in the touchedFields object of the formState.
const form = useForm({
mode: "onChange" // I want to change it to onBlur
});
const { register, handleSubmit, formState } = form;
const { isValid, touchedFields, errors } = formState;
...
<div>
<label htmlFor="firstName">First Name</label>
<input
name="firstName"
placeholder="bill"
{...register("firstName", { minLength: 3 })}
/>
{errors.firstName && touchedFields.firstName && (
<p>"minimum length is 3"</p>
)}
</div>
Working example: https://codesandbox.io/s/react-hook-form-disable-submit-button-onblur-forked-v8m05?file=/src/index.js