What I'm trying to do:
I'm building a complex form and need a way to provide tips and warning messages based on certain conditions (mostly regex) without blocking form submission. Essentially the messages will act as a form of soft validation to help the user complete a higher quality form. I would like to find a solution that plays well with React Hook Form V7.
The Problem:
React Hook Form V7 only supports hard validation (aka blocks form submission). From what I can tell there's no plan to add support this feature in the near future according to this rhf feature request.
Possible Solutions:
There are some V6 solutions proposed in the above rhf feature request such as this one from the creator of rhf:
const PowerController = (props: Props) => {
const { formState } = useFormContext();
const isDirty = !!formState.dirtyFields[props.name];
const isTouched = !!formState.touched[props.name];
return (
<Controller
control={props.control}
name={props.name}
defaultValue={props.defaultValue}
render={(innerProps) => {
return props.render({
...innerProps,
isDirty,
isTouched,
warning: props.warn(innerProps.value)
});
}}
/>
);
};
I also found this answer on how to trigger custom onChange with rhf and the suggestion was to pass an onChange
to Controller
or to useWatch()
. Link here.
I like passing the custom onChange
to Controller
solution but if I understand right doing so would replace the onChange
that's built into Controller
. I'm not sure how to make this work since I'm just trying to add some functionality (aka soft validation on field change).
The solution of useWatch() to see when the value changes then have a separate useEffect()
that I place my soft validation logic in seems reasonable but in a complex form might get real messy??
What I need help with:
Any suggestions on which approach is best and/or ideas on how to adapt the Power Controller V6 solution to work with the V7 Controller would be appreciated. I'm just learning rhf and hoping to get some input before I spend weeks banging my head against a wall trying to solve this lol.
I struggled with the same thing and found out that refactoring the proposed codesandbox solution to work with rhf v7 is not that hard (the sandbox messages when upping the version were actually helpful.
Here is a forked version, I hope it helps -
https://codesandbox.io/s/extend-controller-forked-v7-upgrade-iyw5p0?file=/src/App.tsx