React Hook Form: Dynamic Field Validation Based on Select Input State
I'm working on a project and hit a roadblock. I tried several approaches but none seem to work. I'm working with React Hook Form (version 7.8.0) and I'm working with an scenario with dynamic field validation based on the selected value of a dropdown. I have a form with a select input for choosing a user type (e.g., 'Admin' or 'User'), and I need to conditionally require an additional text input for 'Admin'. My current approach involves using `useEffect` to update the validation schema, but it seems like the validation rules aren't being applied correctly when the user type changes. Here's the relevant code snippet: ```javascript import React, { useEffect } from 'react'; import { useForm, Controller } from 'react-hook-form'; import { yupResolver } from '@hookform/resolvers/yup'; import * as yup from 'yup'; const validationSchema = (userType) => yup.object({ userType: yup.string().required(), adminDetails: userType === 'Admin' ? yup.string().required('Admin details are required') : yup.string().notRequired(), }); const MyForm = () => { const { control, handleSubmit, watch, setValue, trigger } = useForm({ resolver: yupResolver(validationSchema(watch('userType'))), }); const userType = watch('userType'); useEffect(() => { trigger(); // Trigger validation on userType change }, [userType, trigger]); const onSubmit = (data) => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <Controller name='userType' control={control} render={({ field }) => ( <select {...field}> <option value=''>Select User Type</option> <option value='Admin'>Admin</option> <option value='User'>User</option> </select> )} /> <Controller name='adminDetails' control={control} render={({ field }) => <input {...field} placeholder='Admin Details' />} /> <button type='submit'>Submit</button> </form> ); }; ``` The question arises when I change the user type from 'Admin' to 'User' and back again; the validation for `adminDetails` sometimes throws an behavior even if the input is filled. The behavior message I get is: "'adminDetails' must be a `string` type, but the final value was: `undefined`". I tried manually setting `defaultValues` in the `useForm` hook and ensuring that the `validationSchema` is being updated correctly, but I still run into this scenario. Any insights on how to make this conditional validation work consistently?