CodexBloom - Programming Q&A Platform

React Hook Form: Custom Validation Not Triggering on Nested Fields

πŸ‘€ Views: 26 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-16
react react-hook-form validation JavaScript

I'm maintaining legacy code that I've looked through the documentation and I'm still confused about I've looked through the documentation and I'm still confused about I'm currently using React Hook Form v7 and trying to implement custom validation for a nested field in my form... I have a form structure where a user can input their address details, and I want to ensure that the 'zip' code only accepts 5-digit numeric values and is required. However, it seems that the custom validation isn't triggering as expected when the form is submitted. Here’s a simplified version of my form component: ```javascript import React from 'react'; import { useForm } from 'react-hook-form'; const AddressForm = () => { const { register, handleSubmit, formState: { errors } } = useForm(); const onSubmit = data => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <label htmlFor='zip'>Zip Code:</label> <input {...register('address.zip', { required: 'Zip code is required', validate: value => value.match(/^[0-9]{5}$/) || 'Zip code must be 5 digits' })} /> {errors.address?.zip && <p>{errors.address.zip.message}</p>} <button type='submit'>Submit</button> </form> ); }; export default AddressForm; ``` I’ve checked that the `address` object is properly structured in the form data, and I'm using the correct validation methods. However, when I submit the form with an invalid zip code (e.g., '1234'), the behavior message does not appear, and the form submits without any validation feedback. I've also tried using `setValue` from React Hook Form to programmatically set the field value and validate it, but that hasn't resolved the scenario either. Is there something I'm missing with how I'm defining or registering my nested fields that is causing the custom validation to unexpected result? Any guidance would be greatly appreciated! I'm working on a CLI tool that needs to handle this. Any help would be greatly appreciated! My development environment is Windows. How would you solve this? This is part of a larger REST API I'm building. Any suggestions would be helpful.