I am new to React Hook forms. I'm using material UI TextField in my form.
I was able to display the error messages when I type in the Textfield.
But Once I clear the value inside the Textfield and click somewhere else on the page, the error still exists. I do not want it. I only want the errors to be displayed when user is typing in the textfield(example:- email regex check till the valid email is typed) or user submit a form without values.
I do not want the errors to be shown when Textfield is not focused. Can this be achieved by react hook forms?
import { useForm, Controller } from "react-hook-form";
function FormTest(props) {
const {
handleSubmit,
control,
reset,
formState: { isSubmitSuccessful },
} = useForm({ mode: "all" });
const onSubmit = (data) => {
console.log(data);
};
useEffect(() => {
if (isSubmitSuccessful) {
reset();
}
}, [isSubmitSuccessful, reset]);
<form onSubmit={handleSubmit(onSubmit)} noValidate>
<Controller
name="email"
control={control}
defaultValue=''
render={({
field: { onChange, onBlur, value },
fieldState: { error},
}) => (
<TextField
label="Email"
variant="standard"
type="email"
color="warning"
value={value}
onChange={onChange}
onBlur={onBlur}
error={!!error}
helperText ={!!error ? error?.message : ""}
/>
)}
rules={{
required: "Required!",
pattern: {
value: emailPattern,
message: "Invalid Email Address",
},
}}
/>
<Button type="submit">Submit</Button>
</form>
When I click on the TextField and start typing the relevant error is displayed. But once I clear the field and click on a different place in the page the required error still exists. I do not want to show the required error when the text field is not focused. Only if it is focused and submit button is clicked without any values.