react-hook-form-mui
react-hook-form-mui copied to clipboard
If a form field is ever switched to required, it will always be required
Duplicates
- [X] I have searched the existing issues
Latest version
- [x] I have tested the latest version
Current behavior 😯
Please check the demo, if the TextFieldElement or SelectElement is ever switched to required, it will always be required even if the required state is switched back to false.
Expected behavior 🤔
The required state of the form field should correspond to the real state passed from the required attribute.
We found a related issue in RHF, hoping it can help, thanks! https://github.com/react-hook-form/react-hook-form/issues/1749
We found the root cause, RHFM passes the empty object as the rule and leads to the issue, please check the demo, thanks! https://codesandbox.io/p/sandbox/broken-cookies-38y28p
@EkaLinMan, use unregister when changing the isRequired property or anything in rules prop. React Hook Form will then re-register the component with the updated rules in next render.
@sadik-malik, thanks for your reply, we overrode the required rule to fix this issue, this way also works.
{required: required ? "This field is required" : false}
But I'm afraid that the TextFieldElement is not the only one that has this issue. It would be great if RHFM could push a new version to fix all these issues in the future.
@EkaLinMan could you elaborate why providing your own rules is not the solution for this problem? I use the rules object in all my project because I need translated versions of the required error message anyway, that might be the reason why this issue was never present in my projects. To rely on required prop only is just a "lazy" shortcut. I am happy to review a PR though to fix it in your favour.