Skip to content

Validation with nested objects behaves inconsistentlyΒ #171

@matpen

Description

@matpen

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:

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions