Reputation: 8223
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
Upvotes: 8
Views: 10116
Reputation: 81633
That is exactly how onBlur
mode works. From the docs:
Validation will trigger on the blur event.
So when all of your fields become valid, it does not trigger validation. But once you click outside of the currently focused field, the blur
event of that field fires, which runs and passes the validation check, only then the submit button is enabled again.
The solution is to change it back to onChange
mode to trigger validation every time the input value changes.
Upvotes: 4