svelte-forms-lib icon indicating copy to clipboard operation
svelte-forms-lib copied to clipboard

Validation with nested objects behaves inconsistently

Open matpen opened this issue 2 years ago • 1 comments

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:

image

image

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

matpen avatar Jun 07 '22 09:06 matpen

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.

chlrbtlr30 avatar Oct 15 '22 03:10 chlrbtlr30