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

Feature Request: Add abortEarly Mode to Stop Validation at First Error #3884

Open
mhdalmajid opened this issue Dec 5, 2024 · 0 comments
Open

Comments

@mhdalmajid
Copy link

mhdalmajid commented Dec 5, 2024

Zod is a fantastic validation library, but many developers, myself included, face performance challenges when validating data with multiple rules, especially for expensive operations like database queries or HTTP calls. Currently, Zod validates all rules and surfaces as many errors as possible, which is excellent for debugging but not ideal for all use cases.

Problem:

  • In some scenarios, such as form validation or validating HTTP payloads, it’s more efficient to stop validation as soon as the first error is encountered. For example:
    • Validating an email and password where only the first error per field is needed for the user.
    • Avoiding unnecessary, expensive operations (e.g., server requests) after detecting an initial failure.

Proposed Solution:
Introduce an optional abortEarly mode to Zod, similar to how Joi or Yup handle this. When enabled, Zod should stop validation at the first error and return a single issue. This could be implemented as an option in methods like .parse(), .safeParse(), and their async counterparts.

Example:

schema.parse(data, { abortEarly: true });
schema.safeParse(data, { abortEarly: true });
await schema.parseAsync(data, { abortEarly: true });
await schema.safeParseAsync(data, { abortEarly: true });

Benefits:

  • Improved performance by skipping unnecessary validations.
  • Better control over error reporting in scenarios where only one error per field is needed.
  • Enhanced flexibility for developers with diverse use cases.

Additional Notes:
This issue has been discussed extensively in Issue #1403, Issue #1606, and abort on signal Issue #1915.

Many developers have expressed a need for this feature, and alternative solutions like superRefine often result in less readable and more verbose code.

For example:

  • Form validation where only the first error message for each field is displayed.
  • Avoiding redundant checks when basic rules like required fail.

Please reconsider adding this feature to improve developer experience and efficiency.

Thank you for considering this request!

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

No branches or pull requests

1 participant