CodexBloom - Programming Q&A Platform

React Form Validation Not Triggering on Field Blur - Unexpected Behavior

👀 Views: 59 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
react formik yup javascript

I'm trying to debug Quick question that's been bugging me - I'm working with React and using Formik v2 for form handling and validation. I have a simple form with a couple of input fields, and I want to validate the fields when they lose focus (on blur). However, the validation seems to only trigger when the form is submitted, not on blur as expected. I've set up my validation schema using Yup and defined the `validateOnBlur` option in Formik, but it still doesn't seem to work as intended. Here's a snippet 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({ email: Yup.string().email('Invalid email').required('Required'), password: Yup.string().min(6, 'Password must be at least 6 characters').required('Required'), }); const MyForm = () => { return ( <Formik initialValues={{ email: '', password: '' }} validationSchema={validationSchema} validateOnBlur={true} onSubmit={(values) => { console.log(values); }} > {({ handleSubmit }) => ( <Form onSubmit={handleSubmit}> <div> <label>Email</label> <Field name="email" type="email" /> <ErrorMessage name="email" component="div" /> </div> <div> <label>Password</label> <Field name="password" type="password" /> <ErrorMessage name="password" component="div" /> </div> <button type="submit">Submit</button> </Form> )} </Formik> ); }; export default MyForm; ``` Even after enabling `validateOnBlur`, it only validates correctly upon submission. I tried logging the validation process within the form to see if it runs on blur, but it doesn't seem to trigger any validation for the fields. The use case is crucial for user experience, and I want to guide the users as they fill out the form. I also checked that the dependencies are up to date: React v17.0.2 and Formik v2.2.6. Any insights on what I'm doing wrong or how to make sure validations trigger on blur? I would appreciate any help or suggestions! This is part of a larger API I'm building. Has anyone else encountered this? Has anyone dealt with something similar? I recently upgraded to Javascript LTS. Could someone point me to the right documentation?