jquense / yup

Dead simple Object schema validation
MIT License
22.94k stars 935 forks source link

Validating a dynamically created schema results in duplicate errors and stringified arrays as paths #2136

Open keyboardsamurai opened 1 year ago

keyboardsamurai commented 1 year ago

Describe the bug

When I construct a dynamic schema, like below, I will consistently get duplicate errors and the paths look like incorrectly serialized arrays, which is unexpected.

    const mockFormValues = {
      additionalFields: {
        somefield: "123456"
      }
    };

    mockFormValues.additionalFields.somefield = undefined;

    const schemaFields = {
      "additionalFields.somefield": Yup.string()
        .required("This field is required")
        .notOneOf([undefined], "Field is required")
    };

    const schema = Yup.object().shape(schemaFields);

    try {
      await schema.validate(mockFormValues, { abortEarly: false });
    } catch (err) {
      if (err instanceof Yup.ValidationError) {
        expect(err.inner.map((e) => e.path)).toContain(
          "additionalFields.somefield"
        );
      }
    }

This will log the following output:

Expected value: "additionalFields.somefield"
Received array: ["[\"additionalFields.somefield\"]", "[\"additionalFields.somefield\"]"]

To Reproduce

https://codesandbox.io/s/crazy-gould-yr4k7z?file=/src/index.test.js

Expected behavior A clear and concise description of what you expected to happen. I would have expected a single error and a simple string as a path, pointing to additionalFields.somefield

keyboardsamurai commented 1 year ago

Okay, so I have to retract the "duplicate" claim. It looks like this is actually correct behavior since one of the errors is of "type": "notOneOf" and the other has "type": "optionality". Sorry about that. I still think the path in the style of an array might be wrong though.