1

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?

2 Answers 2

6

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> 
Sign up to request clarification or add additional context in comments.

Comments

0

Irfanullah Jan has described why the error is not visible for non-touched fields.

In case you are performing dynamic validation (from a server response or otherwise) and want to include non-touched fields, the imperative version would look like this:

const field = 'username'; const errorMessage = 'Must be present'; formikBag.setFieldTouched(field); formikBag.setFieldError(field, errorMessage); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.