CodexBloom - Programming Q&A Platform

Handling Form Validation with React Hook Form and Custom Input Components

👀 Views: 85 đŸ’Ŧ Answers: 1 📅 Created: 2025-09-06
react react-hook-form javascript JavaScript

I'm a bit lost with I've been struggling with this for a few days now and could really use some help... I'm currently working on a form using React Hook Form (v7.32.0) that includes custom input components. I'm facing an issue where the form validation is not triggering as expected for these custom inputs. For example, I have a custom text input component that integrates with React Hook Form, but the validation seems to be bypassed. Here's how I've set up my component: ```javascript import React from 'react'; import { useForm, Controller } from 'react-hook-form'; const CustomInput = ({ value, onChange, onBlur, error }) => ( <div> <input value={value} onChange={onChange} onBlur={onBlur} type="text" /> {error && <span>{error.message}</span>} </div> ); const MyForm = () => { const { control, handleSubmit, formState: { errors } } = useForm(); const onSubmit = data => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <Controller name="myCustomInput" control={control} rules={{ required: 'This field is required' }} render={({ field }) => ( <CustomInput {...field} error={errors.myCustomInput} /> )} /> <button type="submit">Submit</button> </form> ); }; export default MyForm; ``` When I submit the form without filling `myCustomInput`, it should show the error message 'This field is required'. However, the validation error does not appear, and the form submits successfully without any errors. I've confirmed that the `Controller` is correctly receiving the `field` props, and I've added the required rules for validation, but it's like the validation is not being run at all. I've tried adding `console.log` statements to check whether the rules are applying, but they seem to be ignored altogether. Is there something I'm missing in the integration? Thanks in advance! I've been using Javascript for about a year now. Thanks for your help in advance! This is part of a larger desktop app I'm building. I'd really appreciate any guidance on this.