Formik How to Show Errors When Form Submit

13.3k Views Asked by At
  1. Trying to make validate fields on form submit. (Same time, onblur and onchange must be active too) But when I leave field empty, and submit form. It doesnt give any error.

How can this be possible?

  1. And my second question is; when I post values to my rest api. It may return 400 error, and I want to use these error to my validation fields. Here's my api response:

    { "msg": "Missing required fields", "errors": { "name": [ "validation.required" ], "country": [ "validation.required" ], "city": [ "validation.required" ] } }

It must be let validation errors to name field, city and country fields. How can this be possible?

    <Formik
        initialValues={values}     
        enableReinitialize={true}
        validationSchema={ProductEditSchema}
        validateOnChange={true}
        validateOnBlur={true}
        onSubmit={(values) => {     
          saveLocation(values);
        }}
        >
......
            <Button
              size="large"
              className={classes.button}
              variant="contained"
              color="secondary"      
              onSubmit={() => handleSubmit()}        
            >
              {intl.formatMessage({ id: "GENERAL.SUBMIT" })}
            </Button>
          </Form>
          </>
        )}
      </Formik>
2

There are 2 best solutions below

1
On BEST ANSWER

Well, Formik doesn't automatically handle validation for you, you need to do this yourself. You can write your own validation, which is tiresome, or you can use Yup and create a validation schema, which you can pass into a Formik form (they support Yup validation schemas).

You basically create a validation schema for your data like this:

let schema = yup.object().shape({
  name: yup.string().required(),
  age: yup.number().required().positive().integer(),
  email: yup.string().email(),
  website: yup.string().url(),
  createdOn: yup.date().default(function () {
    return new Date();
  }),
});

You can then pass the schema to your Formik component as a prop:

<Formik
  validationSchema={schema}
  onSubmit={(values) => {
    //Check here if your data is valid
  }}
/>

Here is the Github page for Yup.

Here is the part of Formik's documentation that explains how to integrate Yup and validate (see validationSchema).

0
On

I just noticed that you can compare the formik.submitCount property against the previous value that you can save on a state. Once you check that both are different you can trigger the event and then update your local state variable with the current formik.submitCount. with this implementation you can keep validating on change or on blur.