Skip to content

Schema objects aren't ordered correctly in the error list #2279

Open
@kiikka

Description

@kiikka

Schema objects aren't ordered correctly in the error list. Objects should appear in the list in the same order they are presented in the schema. This works fine with fields, but if you have multiple objects on the same level the ordering of them goes wrong.

Below is a snippet of code you can test this with. It will log the errors out.

import * as yup from 'yup' 

const schema = yup.object({
  testObjects: yup.object().shape({
    object: yup.object().shape({
      field: yup.string().required(),
    }),
    objectC: yup.object().shape({
      field: yup.string().required(),
    }),
    objectB: yup.object().shape({
      field: yup.string().required(),
    }),
  }),
})

// Example data to validate
const data = {
  testObjects: {
    object: {
      field: '',
    },
    objectB: {
      field: '',
    },
    objectC: {
      field: '',
    },
  },
}

async function validateData() {
  try {
    await schema.validate(data, { abortEarly: false }) // `abortEarly: false` to get all errors
    console.log('Validation successful')
  } catch (error) {
    if (error instanceof yup.ValidationError) {
      const errors = error.inner.map((e) => ({
        path: e.path,
        message: e.message,
      }))
      console.log('Validation Errors:', errors)
    }
  }
}

validateData()

The above code will log the following and as you can see testObjects.object is last on the list even though its first in the schema. Its not ordering them alphabetically either. Changing testObjects.objectB and testObjects.objectC order will have effect though, but still testObjects.object will remain last.

[
    {
        "path": "testObjects.objectB.field",
        "message": "testObjects.objectB.field is a required field"
    },
    {
        "path": "testObjects.objectC.field",
        "message": "testObjects.objectC.field is a required field"
    },
    {
        "path": "testObjects.object.field",
        "message": "testObjects.object.field is a required field"
    }
]

Expected behaviour is that all errors are listed in the order they are in the schema.

This is an issue because you can't rely on the top down ordering of the fields anymore when for example pointing out errors on a form.

Platform:

  • Chrome
  • Version 134.0.6998.89

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions