Replies: 3 comments 17 replies
-
Thanks @wdfinch.I think you can pretty sure do that at the resolver now and pass down the context to switch the schema within. is this what you refer to? |
Beta Was this translation helpful? Give feedback.
-
+1 on this. Same use case, we have subforms (sections) inside the main form with conditionally rendered sections. I'd like to place the validation for a section inside the section itself, without piling up everything inside the parent component which makes everything too cumbersome to maintain. A setValidationSchema/updateValidationSchema would be an amazing edition. I'm working on building a custom implementation for my company, if successful I'll share the results here. |
Beta Was this translation helpful? Give feedback.
-
[outdated see the update below]
react-hook-form/src/logic/createFormControl.ts Lines 1420 to 1425 in 61524ae
const { control } = useFormContext<T>();
// ...
if (someCondition) {
// (optional) clearErrors() and revalidate after setting the new schema
control._options = {
resolver: zodResolver(createZodSchema({ type, action })),
}
} Update:A better way I ended up using, is the proposed by the maintainer
const [context, setContext] = useState(...)
const form = useForm<Type>({
context: context,
resolver: (values, context: typeof context, options) => {
// you can return the schema based on context.
// for my use case, I can depend on formValues
const isSomeCondition = values.someValue === someValue;
const createResolver = zodResolver(
getOrderSchema({
type: isSomeCondition ? "some-value" : "some-value-else",
})
);
return createResolver(values, context, options);
},
// ...
}); Then, when RHF needs to validate it will pass formValues, context, and some options react-hook-form/src/logic/createFormControl.ts Lines 405 to 419 in 61524ae |
Beta Was this translation helpful? Give feedback.
-
I had an idea for a feature based on one of my use cases. What do you all think of dynamically being able to change the scheme (yup in my case) of a
useForm
? So for example a method callsetScheme
that could change out a schema at any point.Use case:
I have a parent component that can be passed a child component. The child component has a form in it and the parent doesn't know what child it will receive. The parent needs to know if the child form is valid and manipulate it. Rather than use custom context and repeat logic to sync in all the child forms, it's easier to have the
useForm
hook in the parent and use the useFromContext in the children to communicate. This does mean that the child would choose the schema rather than the parent for validation and it could change as new children are mounted. Would be cool if I could change out the schema easily when a new child form is mounted.Beta Was this translation helpful? Give feedback.
All reactions