Skip to content

Instantly share code, notes, and snippets.

@singh100ful
Last active June 11, 2020 23:43
Show Gist options
  • Save singh100ful/1ea1f748c40a857723e4fc52693c6840 to your computer and use it in GitHub Desktop.
Save singh100ful/1ea1f748c40a857723e4fc52693c6840 to your computer and use it in GitHub Desktop.
FieldArray Validation
<Formik initialValues={{ diet: [] }}
validationSchema={Yup.object().shape({
diet: Yup.array()
.of(
Yup.object().shape({
food_name: Yup.string().required("Required"),
quantity: Yup.string().required("Required"),
})
)
.required("Required"),
})}
>
{(formProps) => (
<Form>
<FieldArray
name="diet"
render={(arrayHelpers) => (
...
<Field
component={CustomInput}
type="text"
name={`diet.${index}.food_name`}
className={
"form-control" +
(formProps.errors.diet && formProps.touched.diet
? formProps.errors.diet[index] && formProps.touched.diet[index]
? formProps.errors.diet[index].food_name && formProps.touched.diet[index].food_name
? " is-invalid"
: ""
: ""
: "")
}
/>
<ErrorMessage
name={`diet.${index}.food_name`}
component="div"
className="invalid-feedback"
/>
...
)}
/>
</Form>
)}
</Formik>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment