CodexBloom - Programming Q&A Platform

React Hook Form: How to Handle Conditional Field Validation Based on User Role

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

I've been struggling with this for a few days now and could really use some help. I'm using React Hook Form v7 to manage my form state and validation. I have a scenario where certain fields should be validated differently based on the user's role (e.g., 'admin' vs. 'user'). For instance, when the user role is 'admin', I need additional fields to be required, but if the role is 'user', those fields should not be required at all. I've tried using the `setValue` and `watch` functions to dynamically control the validation schema, but I'm running into issues where the validation state doesn't seem to reflect the changes when the role updates. Here’s a simplified version of my form setup: ```javascript import { useForm } from 'react-hook-form'; import { useEffect } from 'react'; const MyForm = () => { const { register, handleSubmit, setValue, watch, formState: { errors } } = useForm(); const userRole = watch('role'); // Assuming 'role' is a field in the form useEffect(() => { if (userRole === 'admin') { // Set additional fields to required when role is admin setValue('extraField', '', { shouldValidate: true }); } else { // Clear the field for users, but not required setValue('extraField', null, { shouldValidate: false }); } }, [userRole]); const onSubmit = data => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <select {...register('role')}> <option value='user'>User</option> <option value='admin'>Admin</option> </select> <input {...register('extraField', { required: userRole === 'admin' })} /> {errors.extraField && <p>This field is required for admins</p>} <button type='submit'>Submit</button> </form> ); }; ``` However, I get the validation message for `extraField` even when the role is switched to 'user'. The issue seems to be that the validation doesn't update as expected. I've tried forcing a rerender by changing dependencies, but it hasn't worked. Is there a better way to manage conditional validation in React Hook Form based on user roles? Any best practices or examples would be greatly appreciated! This is part of a larger application I'm building. How would you solve this? Any help would be greatly appreciated!