CodexBloom - Programming Q&A Platform

Form validation optimization guide as expected with Yup and Formik in a React app

👀 Views: 10 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-30
react formik yup validation JavaScript

I'm prototyping a solution and I'm trying to implement I'm working on a form in a React application using Formik for handling form state and Yup for validation. However, I'm working with an scenario where the validation doesn't seem to trigger correctly on certain inputs. Specifically, I have a field for email validation which should show an behavior message if the input doesn't match the correct email format. I am using Formik version 2.2.6 and Yup version 0.32.9. My form component looks like this: ```javascript import React from 'react'; import { Formik, Form, Field, ErrorMessage } from 'formik'; import * as Yup from 'yup'; const validationSchema = Yup.object({ email: Yup.string().email('Invalid email format').required('Email is required'), password: Yup.string().min(6, 'Password must be at least 6 characters').required('Password is required'), }); const MyForm = () => { return ( <Formik initialValues={{ email: '', password: '' }} validationSchema={validationSchema} onSubmit={(values) => { console.log('Form submitted', 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; ``` When I type an invalid email and then try to submit the form, it shows the behavior message correctly. However, if I correct the email and then delete everything from the email input (leaving it empty), the behavior message doesn't appear until I click outside of the field. I expected it to show the 'Email is required' message as soon as the field is submitted. I have tried adding `validateOnChange` and `validateOnBlur` props to the Formik component, but that didn't resolve the scenario. I also checked the documentation to ensure I'm using the right approach. Any ideas on how to fix this so that the validation message appears immediately when leaving the email field empty after having entered a valid email before? This issue appeared after updating to Javascript 3.9. What's the correct way to implement this?