Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(validation-errors): support flattening via flattenValidationErrors function #100

Merged
merged 1 commit into from
Apr 9, 2024

Conversation

TheEdoRan
Copy link
Owner

@TheEdoRan TheEdoRan commented Apr 9, 2024

Sometimes it's better to deal with a flattened error object instead of a formatted one, for instance when you don't need to use nested objects in validation schemas.

This PR exports a function called flattenValidationErrors that does what it says. Be aware that it works just one level deep, as it discards nested schema errors. This is a known limitation of this approach, since it can't prevent key conflicts.

Suppose this is a returned formatted validationErrors object:

validationErrors = {
  _errors: ["Global error"],
  username: {
    _errors: ["Too short", "Username is invalid"],
  },
  email: {
    _errors: ["Email is invalid"],
  }
}

After passing it to flattenValidationErrors:

import { flattenValidationErrors } from "next-safe-action";

const flattenedErrors = flattenValidationErrors(validationErrors);

It becomes this:

flattenedErrors = {
  formErrors: ["Global error"],
  fieldErrors: {
    username: ["Too short", "Username is invalid"],
    email: ["Email is invalid"],
  }
}

Copy link

vercel bot commented Apr 9, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
next-safe-action-example-app ✅ Ready (Inspect) Visit Preview Apr 9, 2024 1:13am
next-safe-action-website ✅ Ready (Inspect) Visit Preview Apr 9, 2024 1:13am

@TheEdoRan TheEdoRan linked an issue Apr 9, 2024 that may be closed by this pull request
1 task
@TheEdoRan TheEdoRan changed the title feat(validation-errors): support errors flattening via flattenValidationErrors function feat(validation-errors): support flattening via flattenValidationErrors function Apr 9, 2024
@TheEdoRan TheEdoRan merged commit 9ae6764 into next Apr 9, 2024
5 checks passed
@TheEdoRan TheEdoRan deleted the flatten-errors branch April 9, 2024 15:58
Copy link

github-actions bot commented Apr 9, 2024

🎉 This PR is included in version 7.0.0-next.19 🎉

The release is available on:

Your semantic-release bot 📦🚀

Copy link

🎉 This PR is included in version 7.0.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant