CodexBloom - Programming Q&A Platform

Form Validation with Formik and Yup: Async Validation Not Triggering with React 18

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

I'm sure I'm missing something obvious here, but I'm collaborating on a project where I'm working with an scenario with form validation using Formik and Yup in my React 18 application... Specifically, I have an asynchronous validation rule that checks if the username already exists in the database, but it doesn't seem to trigger when the user types in the input field. I've set up the validation schema correctly, but I'm not seeing the expected behavior. Here's the relevant code: ```javascript import * as Yup from 'yup'; import { Formik, Form, Field, ErrorMessage } from 'formik'; const validationSchema = Yup.object().shape({ username: Yup.string() .required('Username is required') .test('check-username', 'Username already taken', async (value) => { const response = await fetch(`/api/check-username?username=${value}`); const data = await response.json(); return !data.exists; // Assuming the API returns { exists: true/false } }), }); const MyForm = () => { return ( <Formik initialValues={{ username: '' }} validationSchema={validationSchema} onSubmit={(values) => { console.log('Submitted!', values); }} > {() => ( <Form> <label htmlFor="username">Username:</label> <Field name="username" type="text" /> <ErrorMessage name="username" component="div" /> <button type="submit">Submit</button> </Form> )} </Formik> ); }; ``` The asynchronous validation function is defined as a test within the Yup schema. However, when I type a username and it triggers the validation, the behavior message doesn't appear as expected. I have checked the network tab in the developer tools, and the API call is made correctly, but the validation doesn't seem to reflect the response properly. I've also made sure that my Yup version is 0.32.11 and Formik is 2.2.9. I've tried adding `validateOnChange={true}` and `validateOnBlur={true}` in the Formik component, but that didn't solve the scenario. Additionally, I'm using React's Strict Mode, which has been known to cause some issues in the past. Any insights on what I might be missing or how to debug this would be greatly appreciated! What would be the recommended way to handle this? Has anyone else encountered this?