3.4 KiB
ValidationError
(no submodules)
Purpose
ValidationError is the single error class for the @suaveplan/validation package. It extends SuaveplanError from @suaveplan/error, giving it a stable code (taken from the first issue), a timestamp, and optional traceId. Its issues array carries every ValidationIssue produced during a parse run, enabling rich error reporting for form validation, API input checking, and CLI tools.
The VALIDATION_CODES registry uses defineCodes from @suaveplan/error to produce fully-qualified, type-safe code strings like "VALIDATION.STRING.TOO_SHORT". All 21 validation codes are registered there.
Features
- Extends
SuaveplanError— compatible withwalkCauses,toSpanEvent,toJSON issues: ValidationIssue[]— full list of all parse failures with path and messageflatten()— splits issues intoformErrors(root path) andfieldErrors(field-keyed, dot-separated path)format()— builds a nestedRecord<string, unknown>with_errorsarrays per nodeVALIDATION_CODES— typed registry of all error codes
Usage: Basic Example
import { string } from "@suaveplan/validation";
const result = string().min(5).safeParse("hi");
if (!result.success) {
console.log(result.error.issues);
// [{ code: "VALIDATION.STRING.TOO_SHORT", path: [], message: "..." }]
}
Usage: Advanced Example
import { object, string, number } from "@suaveplan/validation";
const schema = object({ name: string().min(2), age: number().positive() });
const result = schema.safeParse({ name: "A", age: -1 });
if (!result.success) {
const { formErrors, fieldErrors } = result.error.flatten();
// fieldErrors: { name: ["String must be at least 2 character(s)"], age: ["Number must be positive"] }
const formatted = result.error.format();
// { _errors: [], name: { _errors: ["..."] }, age: { _errors: ["..."] } }
}
API Reference
class ValidationError extends SuaveplanError<ValidationCode>
Constructor
new ValidationError(issues: ValidationIssue[], opts?: ValidationErrorOptions)
issues— array ofValidationIssue; the first issue'scodeandmessagebecome the error's primary code and messageopts.cause— optional underlying causeopts.traceId— optional OTel trace id
readonly issues: ValidationIssue[]
All issues collected during parsing.
flatten(): FlattenedErrors
Returns { formErrors: string[], fieldErrors: Record<string, string[]> }. Root-level issues (empty path) go to formErrors; all others are keyed by dot-joined path segments.
format(): Record<string, unknown>
Returns a nested record where each node has an _errors: string[] array. Useful for rendering field-level errors in UI frameworks.
VALIDATION_CODES
Frozen record of all VALIDATION.* codes. Use when constructing custom issues.
ValidationErrorOptions
interface ValidationErrorOptions {
cause?: unknown;
traceId?: string;
}
Implementation Notes
- An empty
issuesarray producescode: "VALIDATION.INVALID_TYPE"and message"Validation failed"as safe fallbacks. format()traverses path segments iteratively, creating intermediate nodes as needed, so deeply nested paths are handled without recursion.flatten()uses a dot-joined path key ("user.address.city") matching the most common form-library convention.