Search code examples
reactjsformik

Formik How to Show Errors When Form Submit


  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>

Solution

  • 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).