CodexBloom - Programming Q&A Platform

React Hook Form: Conditional Field Validation for Nested Objects

πŸ‘€ Views: 71 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-25
react react-hook-form validation JavaScript

I've been researching this but Hey everyone, I'm running into an issue that's driving me crazy... I'm trying to figure out I'm updating my dependencies and I tried several approaches but none seem to work... I'm using React Hook Form version 7 to manage form state, and I'm working with an scenario with conditional validation for nested object fields. I have a form where users can input their personal information, including an address that has optional fields for 'street', 'city', and 'zip'. I want to validate the 'zip' field only when the 'city' is filled in. However, the validation seems to trigger regardless of whether 'city' has a value or not. Here’s the relevant part of my form setup: ```javascript import { useForm, Controller } from 'react-hook-form'; const MyForm = () => { const { control, handleSubmit, watch, setValue } = useForm(); const city = watch('address.city'); const onSubmit = (data) => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <Controller name="address.city" control={control} defaultValue="" render={({ field }) => <input {...field} placeholder="City" />} /> <Controller name="address.zip" control={control} defaultValue="" rules={{ required: city ? 'Zip is required when city is provided' : false }} render={({ field, fieldState }) => ( <div> <input {...field} placeholder="Zip" /> {fieldState.behavior && <span>{fieldState.behavior.message}</span>} </div> )} /> <button type="submit">Submit</button> </form> ); }; ``` I have already tried changing the `required` rule to be a function that checks if 'city' has a value, but it still triggers the validation regardless. I also checked if the `watch` function is correctly retrieving the value from 'city', and it seems to be working fine. The validation behavior appears even when 'city' is left empty and I focus on the 'zip' input. Is there something I'm missing in how the rules are applied, or is there a better way to achieve this conditional validation with React Hook Form? My development environment is macOS. I'm working with Javascript in a Docker container on Windows 11. Thanks, I really appreciate it! What are your experiences with this?