CodexBloom - Programming Q&A Platform

Formik Form Validation Not Triggering on Blur for Input Fields with Nested Schema

πŸ‘€ Views: 23 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
formik react yup javascript

I've been researching this but I've looked through the documentation and I'm still confused about I'm using Formik (version 2.2.6) in my React application to handle form submissions and validations... My form contains a nested structure for user information, and I'm utilizing Yup for schema validation. However, I'm facing a peculiar issue: the validation does not trigger on blur for the fields inside the nested object. Instead, it only validates on submission or when fields are modified. Here’s a simplified version of my code: ```javascript import React from 'react'; import { Formik, Form, Field, ErrorMessage } from 'formik'; import * as Yup from 'yup'; const validationSchema = Yup.object().shape({ user: Yup.object().shape({ name: Yup.string().required('Name is required'), email: Yup.string().email('Invalid email format').required('Email is required'), }) }); const MyForm = () => { return ( <Formik initialValues={{ user: { name: '', email: '' } }} validationSchema={validationSchema} onSubmit={values => { console.log('Form values:', values); }} > {({ handleBlur }) => ( <Form> <div> <label>Name</label> <Field name="user.name" onBlur={handleBlur} /> <ErrorMessage name="user.name" component="div" /> </div> <div> <label>Email</label> <Field name="user.email" onBlur={handleBlur} /> <ErrorMessage name="user.email" component="div" /> </div> <button type="submit">Submit</button> </Form> )} </Formik> ); }; export default MyForm; ``` In this code, I expect the validation messages to appear when the user blurs out of the input fields, but they only show up upon submission or when I change the field value. I have tried using `validateOnBlur` in the Formik configuration, but it does not seem to work as expected for nested fields. Is there a specific approach or setting I might be missing to enable validation on blur for fields nested within an object using Formik and Yup? Any advice would be greatly appreciated! This issue appeared after updating to Javascript 3.11. What would be the recommended way to handle this? This is part of a larger application I'm building. Thanks for your help in advance!