CodexBloom - Programming Q&A Platform

Handling dynamic form validation with Formik and Yup in React

πŸ‘€ Views: 95 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-03
react formik yup validation JavaScript

I'm sure I'm missing something obvious here, but I'm stuck on something that should probably be simple... I'm currently working on a dynamic form using Formik and Yup for validation in a React application. The form allows users to add multiple sections, and each section has its own set of fields that need validation. However, I noticed that when I dynamically add a new section, the validation for that section doesn't trigger as expected. Instead, I receive an error message like `Validation schema is not defined for the field 'sections[1]'`. I have tried using the `setFieldValue` method to update the form values, but it seems that the validation schema isn't being updated correctly. Here's a simplified version of my code: ```jsx import React from 'react'; import { Formik, Form, Field, ErrorMessage } from 'formik'; import * as Yup from 'yup'; const validationSchema = Yup.object().shape({ sections: Yup.array().of( Yup.object().shape({ name: Yup.string().required('Required'), age: Yup.number().required('Required').positive().integer(), }) ) }); const MyForm = () => { return ( <Formik initialValues={{ sections: [{ name: '', age: '' }] }} validationSchema={validationSchema} onSubmit={values => { console.log(values); }} > {({ values, setFieldValue }) => ( <Form> {values.sections.map((section, index) => ( <div key={index}> <Field name={`sections[${index}].name`} placeholder='Name' /> <ErrorMessage name={`sections[${index}].name`} component='div' /> <Field name={`sections[${index}].age`} placeholder='Age' type='number' /> <ErrorMessage name={`sections[${index}].age`} component='div' /> </div> ))} <button type='button' onClick={() => setFieldValue('sections', [...values.sections, { name: '', age: '' }])}> Add Section </button> <button type='submit'>Submit</button> </Form> )} </Formik> ); }; export default MyForm; ``` In this example, when I click the 'Add Section' button, I expect a new section to appear with its own validation, but I'm getting errors like `sections[1]` not being defined in the schema. I’ve confirmed that I am updating the `initialValues` correctly, but the validation schema doesn’t seem to recognize the new section. I've tried various approaches, including resetting the form and explicitly defining the validation schema again after adding a new section, but nothing seems to resolve the issue. Am I missing something in how Formik evaluates the validation schema for dynamically added fields? Any insights would be greatly appreciated! I've been using Javascript for about a year now. Am I missing something obvious? My development environment is CentOS. Am I missing something obvious?