Skip to content

clearErrors

Clear form errors

clearErrors: (name?: string | string[]) => void

This function can manually clear errors in the form.

Rules

  • This will not affect the validation rules attached to each inputs.

  • This function will not update formState (set isValid to true). It only clear errors.

Props

TypeDescriptionExample
undefinedRemove all errors.clearErrors()
stringRemove single error.clearErrors("yourDetails.firstName")
string[]Remove multiple errors.clearErrors(["yourDetails.lastName"])
  • undefined: reset all errors

  • string: 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

import * as React from "react";
import { useForm } from "react-hook-form";

const App = () => {
  const { register, 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>
  );
};
import * as React from "react";
import { useForm } from "react-hook-form";

type FormInputs = {
  firstName: string;
  lastName: string;
  username: string;
};

const App = () => {
  const { register, errors, handleSubmit, clearErrors } = useForm<FormInputs>();

  const onSubmit = (data: FormInputs) => {
    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>
  );
};
Edit