Home > Back-end >  Formik ErrorMessage not displaying for the first time
Formik ErrorMessage not displaying for the first time

Time:08-18

I am using Formik forms in react project. I have the following code inside <Formik><Form>

<Field name="zip" validate={some validation is here}>
       <input {...fieldProps.field}
               id="zip"
               name="zip"
               className="form-control"
               placeholder="zip"
               required={true}
               maxLength={5}
               onKeyDown={(event) => this.onZipChange(event)}/>
</Field>
<ErrorMessage name="zip" render={msg => <div>{msg}</div>} />

When form is rendered, I make changes to the input, for example, remove one number from zip, so in props.formProps.errors errors` texts appear, but ErrorMessage is not displaying. After I click to any places of the page it appears, and then it continue working as expected: on key down it display ErrorMessage if any errors in zip, and hide if zip is valid.

The problem is only for the first time when form is rendered. Any ideas, what can cause the issue?

CodePudding user response:

This is expected behavior. <ErrorMessage /> is only displayed when both of the following conditions are fulfilled:

  • There is an error message for the given field
  • That field's touched property is true

By default, Formik will set touched to true on blur. So this is why the error message only displays when you click outside the input.

If you want to force the error message to appear even before the blur, you may manually set the input's touched property to true. This may be done multiple ways but the simplest is via initialTouched prop on <Formik />. If the form comes preloaded with data from the backend, you may also want to set validateOnMount prop to true.

For example:

<Formik
  validateOnMount
  initialTouched={{zip: true}}
>
  ...
</Formik>
  • Related