I`m trying to make a login form in react using react-hook-form, but when I try to submit with null input values – errors for "password" is getting deleted after rerender. And "login" errors are not being displayed at all.
If I do the same thing with every other registered name (for example "captcha" or "login1/password1"), everything works just fine.
Sandbox: https://codesandbox.io/p/sandbox/8n5rmr?file=%2Fsrc%2FApp.js
Here`s my code:
import React from "react";
import {useForm} from "react-hook-form";
const Login = (props) => {
const {
register, handleSubmit, clearErrors, setError, reset, formState: {
errors
},
} = useForm({
mode: "onBlur", defaultValues: {
login: "", password: "", rememberMe: false, captcha: "",
}
})
const onSubmit = async (data) => {
reset({
login: "", password: "", rememberMe: false, captcha: "",
}, {keepErrors: true});
}
console.log(errors);
console.log(props);
debugger
return (<form
onSubmit={handleSubmit(onSubmit)}
>
<input
{...register("login", {
required: "Login is required", minLength: {
value: 4, message: `Min length is ${4}`
}
})}
placeholder={"Login"}
onFocus={() => clearErrors(["login", "server"])}
/>
<p>{errors.login?.message}</p>
<input
{...register("password", {
required: "Password is required"
})}
placeholder={"Password"}
onFocus={() => clearErrors(["password", "server"])}
/>
<p>{errors.password?.message}</p>
<input
{...register("rememberMe",)}
type={"checkbox"}
/>
<br/>
<input
{...register("captcha", {
required: "Captcha is required"
})}
placeholder={"Captcha"}
onFocus={() => clearErrors(["captcha", "server"])}
/>
<p>{errors.captcha?.message}</p>
<input type={"submit"}/>
</form>)
}
First rerender after submitting with empty inputs
2
Answers
After tinkering around i found out that the form always jumps the focus from first input to second input no matter the order of the inputs, that’s why the errors keep disappearing due to the
onFocus
; one way of work around is usingonClick
instead. I suspect the focus problem is from the libraryreact-hook-form
since the first input should receive focus when the form is submitted.The issue is caused because you are clearing the errors when the inputs get focused.
Focusing fields with error is default behavior of the
react-hook-form
library, you can read about it HERE.You can add
shouldFocusError: false
to your code to prevent the fields from getting focus when they have an error.Here is an example: