Files
promo_steakhouse/src/lib/server-validator.ts
T
lukas cde6899469
CI / test (push) Successful in 5m3s
CI / build (push) Successful in 2m42s
CI / deploy (push) Successful in 16s
✨ first version
2026-08-28 10:12:02 +02:00

18 lines
803 B
TypeScript

import type { z, ZodType } from 'zod'
// `createServerFn().validator(schema)` passes a zod schema straight through to
// TanStack Start, which on failure throws `new Error(JSON.stringify(issues))` —
// the raw issue array, not a message meant for a user to read. Wrapping the
// schema in a plain function (`.validator(zodValidator(schema))`) routes
// validation through this instead, so a rejected field surfaces its own zod
// `.message` (e.g. "Enter a valid phone number") rather than a JSON blob.
export function zodValidator<Schema extends ZodType>(schema: Schema) {
return (input: unknown): z.infer<Schema> => {
const result = schema.safeParse(input)
if (!result.success) {
throw new Error(result.error.issues[0]?.message ?? 'Invalid input')
}
return result.data
}
}