CodexBloom - Programming Q&A Platform

React 18: How to Handle Form Validation with Custom Hooks and External Libraries

👀 Views: 83 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
react react-hook-form yup form-validation custom-hooks JavaScript

I'm refactoring my project and I'm working on a form in React 18 that needs to validate user input using a combination of custom hooks and an external library, `yup`, for schema validation... I have set up my form using `react-hook-form`, but I'm running into issues where the form does not display error messages correctly and sometimes skips validations altogether. I've created a custom hook called `useFormValidation` to handle the validation logic, which looks like this: ```javascript import { useForm } from 'react-hook-form'; import * as yup from 'yup'; import { yupResolver } from '@hookform/resolvers/yup'; const useFormValidation = () => { const schema = yup.object().shape({ username: yup.string().required('Username is required'), email: yup.string().email('Invalid email').required('Email is required'), }); const { register, handleSubmit, formState: { errors } } = useForm({ resolver: yupResolver(schema) }); return { register, handleSubmit, errors }; }; ` In my component, I use this hook like this: ```javascript const MyForm = () => { const { register, handleSubmit, errors } = useFormValidation(); const onSubmit = data => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <div> <input {...register('username')} placeholder="Username" /> {errors.username && <span>{errors.username.message}</span>} </div> <div> <input {...register('email')} placeholder="Email" /> {errors.email && <span>{errors.email.message}</span>} </div> <button type="submit">Submit</button> </form> ); }; ``` However, I'm seeing inconsistent behavior. For instance, when I submit the form without filling in any fields, I get an error for the email field but not for the username, even though both are required. Sometimes the validation messages appear correctly, but other times they don't show up at all. I've also tried adding `console.log(errors)` and noticed that the errors object doesn't always update as expected. I have checked for updates to `react-hook-form` and `yup`, and I'm using `react-hook-form@7.0.0`. Is there anything I'm missing in my setup, or is there a known issue with the way the libraries interact in this specific scenario? For context: I'm using Javascript on CentOS.