Security News
The Risks of Misguided Research in Supply Chain Security
Snyk's use of malicious npm packages for research raises ethical concerns, highlighting risks in public deployment, data exfiltration, and unauthorized testing.
zod-validation-error
Advanced tools
Wrap zod validation errors in user-friendly readable messages.
error.details
;npm install zod-validation-error
import { z as zod } from 'zod';
import { fromZodError } from 'zod-validation-error';
// create zod schema
const zodSchema = zod.object({
id: zod.number().int().positive(),
email: zod.string().email(),
});
// parse some invalid value
try {
zodSchema.parse({
id: 1,
email: 'foobar', // note: invalid email
});
} catch (err) {
const validationError = fromZodError(err);
// the error now is readable by the user
// you may print it to console
// or return it via an API
console.log(validationError);
}
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.
[
{
"code": "too_small",
"inclusive": false,
"message": "Number must be greater than 0",
"minimum": 0,
"path": ["id"],
"type": "number"
},
{
"code": "invalid_string",
"message": "Invalid email",
"path": ["email"],
"validation": "email"
}
]
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)details
- Array<Zod.ZodIssue>; error details (optional)const { ValidationError } = require('zod-validation-error');
const error = new ValidationError('foobar');
console.log(error instanceof Error); // prints true
A type guard utility function, based on instanceof
comparison.
error
- error instance (required)import { ValidationError, isValidationError } from 'zod-validation-error';
const err = new ValidationError('foobar', { details: [] });
isValidationError(err); // returns true
const invalidErr = new Error('foobar');
isValidationError(err); // returns false
A type guard utility function, based on heuristics comparison.
Why do we need heuristics if we have 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.
In most cases, it is safer to use isValidationErrorLike
than isValidationError
.
error
- error instance (required)import { ValidationError, isValidationErrorLike } from 'zod-validation-error';
const err = new ValidationError('foobar', { details: [] });
isValidationErrorLike(err); // returns true
const invalidErr = new Error('foobar');
isValidationErrorLike(err); // returns false
Converts zod error to ValidationError
.
zodError
- zod.ZodError; a ZodError instance (required)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; prefix in user-friendly message (optional, defaults to Validation error
)prefixSeparator
- string; used to concatenate prefix with rest of the user-friendly message (optional, defaults to :
)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
toValidationError(options) => (zodError) => ValidationError
import * as Either from 'fp-ts/Either';
import { z as zod } from 'zod';
import { toValidationError } from 'zod-validation-error';
// create zod schema
const zodSchema = zod
.object({
id: zod.number().int().positive(),
email: zod.string().email(),
})
.brand<'User'>();
export type User = zod.infer<typeof zodSchema>;
export function parse(
value: zod.input<typeof zodSchema>
): Either.Either<Error, User> {
return Either.tryCatch(() => schema.parse(value), toValidationError());
}
Use the isValidationErrorLike
type guard.
Scenario: Distinguish between ValidationError
VS generic Error
in order to respond with 400 VS 500 HTTP status code respectively.
import * as Either from 'fp-ts/Either';
import { z as zod } from 'zod';
import { isValidationErrorLike } from 'zod-validation-error';
try {
func(); // throws Error - or - ValidationError
} catch (err) {
if (isValidationErrorLike(err)) {
return 400; // Bad Data (this is a client error)
}
return 500; // Server Error
}
ValidationError
outside zod
It's possible to implement custom validation logic outside zod
and throw a ValidationError
.
import { ValidationError } from 'zod-validation-error';
import { Buffer } from 'node:buffer';
function parseBuffer(buf: unknown): Buffer {
if (!Buffer.isBuffer(buf)) {
throw new ValidationError('Invalid argument; expected buffer');
}
return buf;
}
zod-validation-error
support CommonJSYes, zod-validation-error
supports CommonJS out-of-the-box. All you need to do is import it using require
.
const { 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
1.2.0
f3aa0b2: Better handling for single-item paths
Given a validation error at array position 1 the error output would read Error X at "[1]"
. After this change, the error output reads Error X at index 1
.
Likewise, previously a validation error at property "_" would yield Error X at "["_"]"
. Now it yieldsError X at "\*"
which reads much better.
FAQs
Wrap zod validation errors in user-friendly readable messages
The npm package zod-validation-error receives a total of 1,476,168 weekly downloads. As such, zod-validation-error popularity was classified as popular.
We found that zod-validation-error demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Snyk's use of malicious npm packages for research raises ethical concerns, highlighting risks in public deployment, data exfiltration, and unauthorized testing.
Research
Security News
Socket researchers found several malicious npm packages typosquatting Chalk and Chokidar, targeting Node.js developers with kill switches and data theft.
Security News
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.