'React Hook form clear errors on click
I'm implementing validation into my application, currently everything is working, the user gets an error message on wrong input and so on. The only thing I have left to do is to implement a field reset, if the user's input corresponds to the requirements of the validator.
I'm using React-Hook-Form and React yup. If I now click out of a field and it is empty, an error gets shown, if I click in again and type something then the error goes away. BUT if I click out into another field the error message stays there, even though the input is correct. Now this obviously isn't how I want it to work.
Here are my yup and react hook form variables
const providerSchema = yup.object().shape({
name: yup.string().required(),
parent: yup.string().required().min(3),
website: yup.string().required().matches(/^(https:|http:|www\\.)\\S*/gm),
street: yup.string().required().min(3),
city: yup.string().required().min(2),
zipCode: yup.number().required().min(4),
country: yup.number().required()
});
const { register, handleSubmit, formState: {errors}, clearErrors } = useForm({ mode: "onTouched", reValidateMode: "onChange" , resolver: yupResolver(providerSchema)});
And here are two of multiple fields I'm using in the form:
<div>
<div className="mb-3">
<label className={`${errors.street ? "text-red-700" : "text-black-400"}`}>Street</label>
<input {...register("street")} id="street" className={`${
errors.street ? "text-red-600 border-red-400"
: "text-black-200 border-black-400"}`} type="text" placeholder="Street" ref=
{streetRef} onChange={() => clearErrors()}/>
{errors.street && (
<p className="text-red-500 text-sm mt-2">
Street is required.
</p>
)}
</div>
</div>
<div className="mb-3">
<label className={`${errors.city ? "text-red-700" : "text-black-400"}`}>City</label>
<input {...register("city")} id="city" className={`${
errors.city ? "text-red-600 border-red-400"
: "text-black-200 border-black-400"}`} type="text" placeholder="City" ref={cityRef}
onChange={() => clearErrors()}/>
{errors.city && (
<p className="text-red-500 text-sm mt-2">
City is required.
</p>
)}
</div>
Solution 1:[1]
May be issue with schema or with setup w schema-
from rhf examples:
const schema = yup.object({
firstName: yup.string().required(),
age: yup.number().positive().integer().required(),
}).required();
Try removing mode: "onTouched"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rbtmr |
