Feature Request: Add abortEarly Mode to Stop Validation at First Error
mhdalmajid opened this issue · 0 comments
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!