-
-
Notifications
You must be signed in to change notification settings - Fork 2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Array prototype breaks react-hook-form validation #9037
Comments
The problem does not occur if I use if (!Array.prototype.myMethod) {
Object.defineProperty(Array.prototype, 'myMethod', {
value: function () {
return true;
},
writable: false
});
} |
I've added another side-effect to the sandbox: the |
Thanks for reporting the issue. The root cause is from util "cloneObject" which shallow copy object when there is a function inside object properties. react-hook-form/src/utils/cloneObject.ts Lines 17 to 22 in 104314d
In this case, array has new prototype method "myMethod" therefore the whole array is kept as a shallow copy instead of deep clone and lead to share same reference between "defaultValues" and "formValues" which causes wrong form state checking (invalid , dirty). @bluebill1049 : Can we add a double check "!Array.isArray(data)" before shallow copy "data" at line 19 ? May be adding "hasOwnProperty" when using "for ... in ..." following javascript best practice to avoid any potential issue related to "prototype" is considered too. NOTE: Using "Object.defineProperty" will bypass the issue because default setting "enumerable" is false therefore custom method "myMethod" will not show on "for ... in ..." loop. |
Thanks for the investigation @leapful This is something we try to avoid with |
@bluebill1049 Just to make sure you are aware: |
I would most definitely expect a forms library to properly support DateTime objects. I'm honestly kinda surprised that it's not supported right now. It's pretty common to have datetime fields in a form. I have a form with multiple fields, one of the fields is a DateTimePicker from mui, therefore I have a luxon DateTime object in my form and the .now value as a default. Is this really not supported? |
Version Number
7.35.0
Codesandbox/Expo snack
https://codesandbox.io/s/rhf-validation-issue-2cyqbk?file=/src/App.js
Steps to reproduce
Array.prototype
from anywhere in codeuseFieldArray
with a required fieldExpected behaviour
When submitting the form with the required field filled no validation error should occur.
Extra methods on
Array.prototype
(not overrides) should not affectreact-hook-form
What browsers are you seeing the problem on?
Firefox, Chrome, Edge
Relevant log output
No response
Code of Conduct
The text was updated successfully, but these errors were encountered: