CodexBloom - Programming Q&A Platform

React Final Form: Handling Dynamic Field Arrays and Validation on Submit

πŸ‘€ Views: 679 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-13
react final-form form-validation javascript

I need some guidance on Quick question that's been bugging me - I'm working on a project and hit a roadblock... I tried several approaches but none seem to work. I'm working with React Final Form to create a dynamic form where users can add or remove address entries, each with its own validation. The problem arises when I try to validate these fields on form submission. Despite implementing the validation function, it seems to be skipping over the dynamically added fields unless they have been touched or modified. I want to ensure that all fields are validated when the form is submitted, regardless of their current state. Here’s a simplified version of my form structure: ```javascript import React from 'react'; import { Form, Field, FieldArray } from 'react-final-form'; const validate = values => { const errors = {}; if (!values.addresses || !values.addresses.length) { errors.addresses = { _error: 'At least one address must be entered' }; } values.addresses.forEach((address, index) => { if (!address || !address.street) { errors.addresses[index] = { street: 'Required' }; } if (!address || !address.city) { errors.addresses[index] = { city: 'Required' }; } }); return errors; }; const AddressForm = () => { return ( <Form onSubmit={formValues => console.log(formValues)} validate={validate} render={({ handleSubmit, submitting, pristine, form }) => ( <form onSubmit={handleSubmit}> <FieldArray name="addresses"> {({ fields }) => ( <div> {fields.map((name, index) => ( <div key={name}> <Field name={`${name}.street`} component="input" placeholder="Street" /> <Field name={`${name}.city`} component="input" placeholder="City" /> <button type="button" onClick={() => fields.remove(index)}>Remove</button> </div> ))} <button type="button" onClick={() => fields.push({})}>Add Address</button> </div> )} </FieldArray> <button type="submit" disabled={submitting || pristine}>Submit</button> </form> )} /> ); }; export default AddressForm; ``` When I hit submit without modifying any of the dynamically added address fields, I get an empty object in the console. I’ve tried using the `validate` function directly on each field, but it still only validates touched fields. Is there a way to force validation on all address fields at submit, or is there a different strategy I should be using for dynamic fields in React Final Form? For context: I'm using Javascript on Windows. I'm developing on Windows 10 with Javascript. Any feedback is welcome! I'm coming from a different tech stack and learning Javascript.