- 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?
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>
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:
You can then pass the schema to your Formik component as a prop:
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
).