Formik reset errors

Viewed 22014

I am trying to reset all errors in the form.

I tried using setErrors and setStatus, none of these are working. Errors in Formik state is not getting cleared.

setErrors({errors: {}})

and

setStatus({ errors: {}});

None of the above worked.

resetForm() clears all errors, but the form values are also reset which I don't want. Any pointers to clear only the errors object?

3 Answers

While using setErrors, just pass the state of errors object you want. So to reset all errors, pass an empty object({}).

setErrors({})

Codesandbox demo here.

The accepted answer did not work for me.

What worked is:

formik.setTouched({}, false);

You can also use form.setFieldTouched (fieldName, false, false) to reset a single field.

Here is example where checking checkbox will clear the value and error form the date field.

<Field name={'expiry'}>
  {({
    field,
    form,
  }) => (
    <Checkbox
      {...field}
      onChange={(e) => {
        field.onChange(e)
        form.setFieldValue('date', '')
        form.setFieldTouched('date', false, false)
      }}
    />
  )}
</Field>

Related