toValidationError
toValidationError is a curried version of fromError, designed specifically for developers using Functional Programming (FP) paradigms or Promise chains.
Signature
function toValidationError(
options?: FromZodErrorOptions
): (err: unknown) => ValidationError
Description
Currying is a technique where a function that takes multiple arguments is evaluated as a sequence of functions, each taking a single argument.
toValidationError behaves exactly like fromError, meaning it is forgiving, handles unknown inputs safely, and formats Zod errors beautifully. However, instead of executing immediately, it:
- Takes your configuration
optionsfirst. - Returns a new function.
- That new function takes the
errpayload and returns the finalValidationError.
This makes it exceptionally clean to use as a callback in .catch() blocks or functional tryCatch wrappers.
Examples
Usage with Promises
When validating asynchronous Zod schemas (parseAsync), standard promise chaining allows you to pass the curried function directly into .catch().
import { z as zod } from 'zod';
import { toValidationError } from 'zod-validation-error';
const asyncSchema = zod.object({
username: zod.string().refine(async (val) => await checkDb(val), "Username taken")
});
// Traditional approach:
// asyncSchema.parseAsync(data).catch(err => throw fromError(err, { prefix: 'DB Error' }));
// Point-free approach with toValidationError:
asyncSchema.parseAsync(data)
.then(validData => console.log("Success:", validData))
.catch(toValidationError({ prefix: 'DB Error' }))
.then(validationError => console.log(validationError.message));
Usage with Functional Libraries (fp-ts)
Libraries like fp-ts rely heavily on curried functions and Monads (like Either) for safe, error-free code paths.
import * as Either from 'fp-ts/Either';
import { z as zod } from 'zod';
import { toValidationError, ValidationError } from 'zod-validation-error';
const schema = zod.object({
id: zod.number().int().positive(),
email: zod.string().email(),
});
export type User = zod.infer<typeof schema>;
// Functional parse function returning an Either type
export function safeParseUser(value: unknown): Either.Either<ValidationError, User> {
return Either.tryCatch(
() => schema.parse(value),
// Automatically ingests the error from tryCatch and formats it
toValidationError({ issueSeparator: '\n' })
);
}
// Consuming the Either
const result = safeParseUser({ id: -1, email: 'bad' });
if (Either.isLeft(result)) {
// We have a guaranteed ValidationError
console.error(result.left.message);
}