svelte-forms-lib
svelte-forms-lib copied to clipboard
Validation with nested objects behaves inconsistently
Summary
According to my tests, the validation with nested object behaves in two different ways:
- keys are actually nested (as expected) when validating the whole form (eg. on submit);
- keys are concatenated (with dots) when validating a single field (eg. on edit).
This makes writing custom validation routines very hard, because both cases are to be considered. Also, the ErrorMessage
component does not work in these cases, because this code expects a single dotted key, while in most cases the error is nested.
Steps to reproduce
Try a form with a nested schema, eg. like the following one. See below for a sandbox.
const initialValues = {
name: "",
email: "",
address: {
city: "",
street: ""
},
};
Example Project
In this CodeSandbox I adapted the example from the docs to a nested object, as described in this issue.
What is the current bug behavior?
In the above sandbox, insert values in all fields, and submit the form: this validates the whole form, and correctly displays the result. Now go ahead and clear the values in the city
and street
fields: the validation now runs on a single value at the time (the one being edited) and does not display an error, because the key is now different.
What is the expected correct behavior?
There should be only one supported way of using keys.
Relevant logs and/or screenshots
No logs available. Screenshot of the buggy behavior from the sandbox linked above:
Possible fixes
My current solution in consumer code is to detect "dotted" keys in the validate
callback, and act accordingly: if the passed key contains dots, then the error keys must have dots, too. However, accessing the values must still be done in nested mode. This makes for very complex code.
The solution in the library code should probably focus on cases like this, where the code incorrectly assumes a flat structure.
Possibly related issues, unsure if regression:
- https://github.com/tjinauyeung/svelte-forms-lib/issues/115
- https://github.com/tjinauyeung/svelte-forms-lib/issues/125
I've searched this issue for two fucking days. Thanks for report this bug. It is nonsense why should I tagging all ids and names.