Gathering detailed insights and metrics for zod-validation-error
Gathering detailed insights and metrics for zod-validation-error
Gathering detailed insights and metrics for zod-validation-error
Gathering detailed insights and metrics for zod-validation-error
Wrap zod validation errors in user-friendly readable messages
npm install zod-validation-error
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
819 Stars
422 Commits
11 Forks
11 Watching
33 Branches
25 Contributors
Updated on 26 Nov 2024
Minified
Minified + Gzipped
TypeScript (98.79%)
JavaScript (0.67%)
Shell (0.54%)
Cumulative downloads
Total Downloads
Last day
-6%
351,487
Compared to previous day
Last week
3.7%
1,963,872
Compared to previous week
Last month
20.3%
8,469,472
Compared to previous month
Last year
862.3%
47,793,119
Compared to previous year
1
22
Wrap zod validation errors in user-friendly readable messages.
error.details
;1npm install zod-validation-error
1import { z as zod } from 'zod'; 2import { fromError } from 'zod-validation-error'; 3 4// create zod schema 5const zodSchema = zod.object({ 6 id: zod.number().int().positive(), 7 email: zod.string().email(), 8}); 9 10// parse some invalid value 11try { 12 zodSchema.parse({ 13 id: 1, 14 email: 'foobar', // note: invalid email 15 }); 16} catch (err) { 17 const validationError = fromError(err); 18 // the error is now readable by the user 19 // you may print it to console 20 console.log(validationError.toString()); 21 // or return it as an actual error 22 return validationError; 23}
Zod errors are difficult to consume for the end-user. This library wraps Zod validation errors in user-friendly readable messages that can be exposed to the outer world, while maintaining the original errors in an array for dev use.
1[ 2 { 3 "code": "too_small", 4 "inclusive": false, 5 "message": "Number must be greater than 0", 6 "minimum": 0, 7 "path": ["id"], 8 "type": "number" 9 }, 10 { 11 "code": "invalid_string", 12 "message": "Invalid email", 13 "path": ["email"], 14 "validation": "email" 15 } 16]
Validation error: Number must be greater than 0 at "id"; Invalid email at "email"
Main ValidationError
class, extending native JavaScript Error
.
message
- string; error message (required)options
- ErrorOptions; error options as per JavaScript definition (optional)
options.cause
- any; can be used to hold the original zod error (optional)message
1const { ValidationError } = require('zod-validation-error'); 2 3const error = new ValidationError('foobar'); 4console.log(error instanceof Error); // prints true
message
and options.cause
1import { z as zod } from 'zod'; 2const { ValidationError } = require('zod-validation-error'); 3 4const error = new ValidationError('foobar', { 5 cause: new zod.ZodError([ 6 { 7 code: 'invalid_string', 8 message: 'Invalid email', 9 path: ['email'], 10 validation: 'email', 11 }, 12 ]), 13}); 14 15console.log(error.details); // prints issues from zod error
Creates zod-validation-error's default MessageBuilder
, which is used to produce user-friendly error messages.
Meant to be passed as an option to fromError, fromZodIssue, fromZodError or toValidationError.
You may read more on the concept of the MessageBuilder
further below.
props
- Object; formatting options (optional)
maxIssuesInMessage
- number; max issues to include in user-friendly message (optional, defaults to 99)issueSeparator
- string; used to concatenate issues in user-friendly message (optional, defaults to ";")unionSeparator
- string; used to concatenate union-issues in user-friendly message (optional, defaults to ", or")prefix
- string or null; prefix to use in user-friendly message (optional, defaults to "Validation error"). Pass null
to disable prefix completely.prefixSeparator
- string; used to concatenate prefix with rest of the user-friendly message (optional, defaults to ": "). Not used when prefix
is null
.includePath
- boolean; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to true
).1import { createMessageBuilder } from 'zod-validation-error'; 2 3const messageBuilder = createMessageBuilder({ 4 includePath: false, 5 maxIssuesInMessage: 3 6});
A custom error map to use with zod's setErrorMap
method and get user-friendly messages automatically.
1import { z as zod } from 'zod'; 2import { errorMap } from 'zod-validation-error'; 3 4zod.setErrorMap(errorMap);
A type guard utility function, based on instanceof
comparison.
error
- error instance (required)1import { z as zod } from 'zod'; 2import { ValidationError, isValidationError } from 'zod-validation-error'; 3 4const err = new ValidationError('foobar'); 5isValidationError(err); // returns true 6 7const invalidErr = new Error('foobar'); 8isValidationError(err); // returns false
A type guard utility function, based on heuristics comparison.
Why do we need heuristics since we can use a simple instanceof
comparison? Because of multi-version inconsistencies. For instance, it's possible that a dependency is using an older zod-validation-error
version internally. In such case, the instanceof
comparison will yield invalid results because module deduplication does not apply at npm/yarn level and the prototype is different.
tl;dr if you are uncertain then it is preferable to use isValidationErrorLike
instead of isValidationError
.
error
- error instance (required)1import { ValidationError, isValidationErrorLike } from 'zod-validation-error'; 2 3const err = new ValidationError('foobar'); 4isValidationErrorLike(err); // returns true 5 6const invalidErr = new Error('foobar'); 7isValidationErrorLike(err); // returns false
A type guard utility function, based on heuristics comparison.
Why do we need heuristics since we can use a simple instanceof
comparison? Because of multi-version inconsistencies. For instance, it's possible that a dependency is using an older zod
version internally. In such case, the instanceof
comparison will yield invalid results because module deduplication does not apply at npm/yarn level and the prototype is different.
error
- error instance (required)1import { z as zod } from 'zod'; 2import { ValidationError, isZodErrorLike } from 'zod-validation-error'; 3 4const zodValidationErr = new ValidationError('foobar'); 5isZodErrorLike(zodValidationErr); // returns false 6 7const genericErr = new Error('foobar'); 8isZodErrorLike(genericErr); // returns false 9 10const zodErr = new zod.ZodError([ 11 { 12 code: zod.ZodIssueCode.custom, 13 path: [], 14 message: 'foobar', 15 fatal: true, 16 }, 17]); 18isZodErrorLike(zodErr); // returns true
Converts an error to ValidationError
.
What is the difference between fromError
and fromZodError
? The fromError
function is a less strict version of fromZodError
. It can accept an unknown error and attempt to convert it to a ValidationError
.
error
- unknown; an error (required)options
- Object; formatting options (optional)
messageBuilder
- MessageBuilder; a function that accepts an array of zod.ZodIssue
objects and returns a user-friendly error message in the form of a string
(optional).Alternatively, you may pass the following options
instead of a messageBuilder
.
options
- Object; formatting options (optional)
maxIssuesInMessage
- number; max issues to include in user-friendly message (optional, defaults to 99)issueSeparator
- string; used to concatenate issues in user-friendly message (optional, defaults to ";")unionSeparator
- string; used to concatenate union-issues in user-friendly message (optional, defaults to ", or")prefix
- string or null; prefix to use in user-friendly message (optional, defaults to "Validation error"). Pass null
to disable prefix completely.prefixSeparator
- string; used to concatenate prefix with rest of the user-friendly message (optional, defaults to ": "). Not used when prefix
is null
.includePath
- boolean; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to true
).They will be passed as arguments to the createMessageBuilder function. The only reason they exist is to provide backwards-compatibility with older versions of zod-validation-error
. They should however be considered deprecated and may be removed in the future.
Converts a single zod issue to ValidationError
.
zodIssue
- zod.ZodIssue; a ZodIssue instance (required)options
- Object; formatting options (optional)
messageBuilder
- MessageBuilder; a function that accepts an array of zod.ZodIssue
objects and returns a user-friendly error message in the form of a string
(optional).Alternatively, you may pass the following options
instead of a messageBuilder
.
options
- Object; formatting options (optional)
issueSeparator
- string; used to concatenate issues in user-friendly message (optional, defaults to ";")unionSeparator
- string; used to concatenate union-issues in user-friendly message (optional, defaults to ", or")prefix
- string or null; prefix to use in user-friendly message (optional, defaults to "Validation error"). Pass null
to disable prefix completely.prefixSeparator
- string; used to concatenate prefix with rest of the user-friendly message (optional, defaults to ": "). Not used when prefix
is null
.includePath
- boolean; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to true
).They will be passed as arguments to the createMessageBuilder function. The only reason they exist is to provide backwards-compatibility with older versions of zod-validation-error
. They should however be considered deprecated and may be removed in the future.
Converts zod error to ValidationError
.
Why is the difference between ZodError
and ZodIssue
? A ZodError
is a collection of 1 or more ZodIssue
instances. It's what you get when you call zodSchema.parse()
.
zodError
- zod.ZodError; a ZodError instance (required)options
- Object; formatting options (optional)
messageBuilder
- MessageBuilder; a function that accepts an array of zod.ZodIssue
objects and returns a user-friendly error message in the form of a string
(optional).Alternatively, you may pass the following options
instead of a messageBuilder
.
options
- Object; formatting options (optional)
user-friendly message (optional, defaults to 99)
issueSeparator
- string; used to concatenate issues in user-friendly message (optional, defaults to ";")unionSeparator
- string; used to concatenate union-issues in user-friendly message (optional, defaults to ", or")prefix
- string or null; prefix to use in user-friendly message (optional, defaults to "Validation error"). Pass null
to disable prefix completely.prefixSeparator
- string; used to concatenate prefix with rest of the user-friendly message (optional, defaults to ": "). Not used when prefix
is null
.includePath
- boolean; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to true
).They will be passed as arguments to the createMessageBuilder function. The only reason they exist is to provide backwards-compatibility with older versions of zod-validation-error
. They should however be considered deprecated and may be removed in the future.
A curried version of fromZodError
meant to be used for FP (Functional Programming). Note it first takes the options object if needed and returns a function that converts the zodError
to a ValidationError
object
1toValidationError(options) => (zodError) => ValidationError
1import * as Either from 'fp-ts/Either'; 2import { z as zod } from 'zod'; 3import { toValidationError, ValidationError } from 'zod-validation-error'; 4 5// create zod schema 6const zodSchema = zod 7 .object({ 8 id: zod.number().int().positive(), 9 email: zod.string().email(), 10 }) 11 .brand<'User'>(); 12 13export type User = zod.infer<typeof zodSchema>; 14 15export function parse( 16 value: zod.input<typeof zodSchema> 17): Either.Either<ValidationError, User> { 18 return Either.tryCatch(() => schema.parse(value), toValidationError()); 19}
zod-validation-error
can be configured with a custom MessageBuilder
function in order to produce case-specific error messages.
For instance, one may want to print invalid_string
errors to the console in red color.
1import { z as zod } from 'zod'; 2import { type MessageBuilder, fromError } from 'zod-validation-error'; 3import chalk from 'chalk'; 4 5// create custom MessageBuilder 6const myMessageBuilder: MessageBuilder = (issues) => { 7 return issues 8 // format error message 9 .map((issue) => { 10 if (issue.code === zod.ZodIssueCode.invalid_string) { 11 return chalk.red(issue.message); 12 } 13 14 return issue.message; 15 }) 16 // join as string with new-line character 17 .join('\n'); 18} 19 20// create zod schema 21const zodSchema = zod.object({ 22 id: zod.number().int().positive(), 23 email: zod.string().email(), 24}); 25 26// parse some invalid value 27try { 28 zodSchema.parse({ 29 id: 1, 30 email: 'foobar', // note: invalid email value 31 }); 32} catch (err) { 33 const validationError = fromError(err, { 34 messageBuilder: myMessageBuilder 35 }); 36 // the error is now displayed with red letters 37 console.log(validationError.toString()); 38} 39
Use the isValidationErrorLike
type guard.
Scenario: Distinguish between ValidationError
VS generic Error
in order to respond with 400 VS 500 HTTP status code respectively.
1import * as Either from 'fp-ts/Either'; 2import { z as zod } from 'zod'; 3import { isValidationErrorLike } from 'zod-validation-error'; 4 5try { 6 func(); // throws Error - or - ValidationError 7} catch (err) { 8 if (isValidationErrorLike(err)) { 9 return 400; // Bad Data (this is a client error) 10 } 11 12 return 500; // Server Error 13}
ValidationError
outside zod
It's possible to implement custom validation logic outside zod
and throw a ValidationError
.
1import { ValidationError } from 'zod-validation-error'; 2import { Buffer } from 'node:buffer'; 3 4function parseBuffer(buf: unknown): Buffer { 5 if (!Buffer.isBuffer(buf)) { 6 throw new ValidationError('Invalid argument; expected buffer'); 7 } 8 9 return buf; 10}
1import { ValidationError } from 'zod-validation-error'; 2 3try { 4 // do something that throws an error 5} catch (err) { 6 throw new ValidationError('Something went deeply wrong', { cause: err }); 7}
ValidationError
with custom "error map"Zod supports customizing error messages by providing a custom "error map". You may combine this with zod-validation-error
to produce user-friendly messages.
errorMap
propertyIf all you need is to produce user-friendly error messages you may use the errorMap
property.
1import { z as zod } from 'zod'; 2import { errorMap } from 'zod-validation-error'; 3 4zod.setErrorMap(errorMap);
fromZodIssue
If you need to customize some error code, you may use the fromZodIssue
function.
1import { z as zod } from 'zod'; 2import { fromZodIssue } from 'zod-validation-error'; 3 4const customErrorMap: zod.ZodErrorMap = (issue, ctx) => { 5 switch (issue.code) { 6 case ZodIssueCode.invalid_type: { 7 return { 8 message: 9 'Custom error message of your preference for invalid_type errors', 10 }; 11 } 12 default: { 13 const validationError = fromZodIssue({ 14 ...issue, 15 // fallback to the default error message 16 // when issue does not have a message 17 message: issue.message ?? ctx.defaultError, 18 }); 19 20 return { 21 message: validationError.message, 22 }; 23 } 24 } 25}; 26 27zod.setErrorMap(customErrorMap);
zod-validation-error
with react-hook-form
?1import { useForm } from 'react-hook-form'; 2import { zodResolver } from '@hookform/resolvers/zod'; 3import { errorMap } from 'zod-validation-error'; 4 5useForm({ 6 resolver: zodResolver(schema, { errorMap }), 7});
zod-validation-error
support CommonJSYes, zod-validation-error
supports CommonJS out-of-the-box. All you need to do is import it using require
.
1const { ValidationError } = require('zod-validation-error');
Source code contributions are most welcome. Please open a PR, ensure the linter is satisfied and all tests pass.
Causaly is building the world's largest biomedical knowledge platform, using technologies such as TypeScript, React and Node.js. Find out more about our openings at https://apply.workable.com/causaly/.
MIT
No vulnerabilities found.
No security vulnerabilities found.