clearErrors: (name?: string | string[]) => void
This function can manually clear errors in the form.
Props
Type | Description | Example |
---|---|---|
undefined | Remove all errors. | clearErrors() |
string | Remove single error. | clearErrors("yourDetails.firstName") |
string[] | Remove multiple errors. | clearErrors(["yourDetails.lastName"]) |
undefined
: reset all errorsstring
: reset the error on a single field or by key name.register('test.firstName', { required: true }); register('test.lastName', { required: true }); clearErrors('test'); // will clear both errors from test.firstName and test.lastName clearErrors('test.firstName'); // for clear single input error
string[]
: reset errors on the given fields
Rules
This will not affect the validation rules attached to each inputs.
This method doesn't affect validation rules or
isValid
formState.
Examples
import * as React from "react";
import { useForm } from "react-hook-form";
export default function App() {
const { register, formState: { errors }, handleSubmit, clearErrors } = useForm();
const onSubmit = data => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('firstName', { required: true })} />
<input {...register('lastName', { required: true })} />
<input {...register('username', { required: true })} />
<button type="button" onClick={() => clearErrors("firstName")}>
Clear First Name Errors
</button>
<button
type="button"
onClick={() => clearErrors(["firstName", "lastName"])}
>
Clear First and Last Name Errors
</button>
<button type="button" onClick={() => clearErrors()}>
Clear All Errors
</button>
<input type="submit" />
</form>
);
};
Thank you for your support
If you find React Hook Form to be useful in your project, please consider to star and support it.