CodexBloom - Programming Q&A Platform

Handling Form Submission with React Hook Form and Custom Validation Logic for Date Inputs

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

I just started working with I'm integrating two systems and I'm reviewing some code and I'm currently working on a form using React Hook Form (v7.0.0) and I'm working with issues with custom validation logic for date inputs. My form includes a start date and an end date, and I need to ensure that the end date is always later than the start date. When I submit the form with invalid dates, I don't see the custom behavior message I expect. Instead, the form just submits without any validation feedback. Here's the code I've written for the form: ```javascript import React from 'react'; import { useForm } from 'react-hook-form'; const MyForm = () => { const { register, handleSubmit, setError, formState: { errors } } = useForm(); const onSubmit = (data) => { console.log(data); }; const validateDates = (startDate, endDate) => { if (new Date(startDate) >= new Date(endDate)) { setError('endDate', { type: 'manual', message: 'End date must be later than start date', }); } }; return ( <form onSubmit={handleSubmit(onSubmit)}> <input type='date' {...register('startDate', { required: true })} /> <input type='date' {...register('endDate', { required: true })} onChange={(e) => validateDates(document.querySelector('[name="startDate"]').value, e.target.value)} /> {errors.endDate && <span>{errors.endDate.message}</span>} <button type='submit'>Submit</button> </form> ); }; export default MyForm; ``` I've tried moving the validation logic to the `onSubmit` function instead, but that doesn't help since the form still submits before the validation check completes. I've also confirmed that the `setError` function is being called, but the behavior message does not appear as expected. Is there a better way to handle this validation within React Hook Form? Any guidance on how to ensure that my form respects the custom validation logic would be greatly appreciated! I'm working on a CLI tool that needs to handle this. Any examples would be super helpful. I'm working on a mobile app that needs to handle this. Is there a simpler solution I'm overlooking? I'm working in a Windows 11 environment.