react-hook-form-mui icon indicating copy to clipboard operation
react-hook-form-mui copied to clipboard

If a form field is ever switched to required, it will always be required

Open EkaLinMan opened this issue 1 year ago • 5 comments
trafficstars

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.

EkaLinMan avatar Aug 19 '24 06:08 EkaLinMan

We found a related issue in RHF, hoping it can help, thanks! https://github.com/react-hook-form/react-hook-form/issues/1749

EkaLinMan avatar Aug 19 '24 07:08 EkaLinMan

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

image

EkaLinMan avatar Sep 03 '24 02:09 EkaLinMan

@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 avatar Sep 03 '24 18:09 sadik-malik

@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 avatar Sep 04 '24 03:09 EkaLinMan

@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.

dohomi avatar Oct 10 '24 01:10 dohomi