Replies: 1 comment
-
|
You can't safely extend the The idiomatic way to share custom validations (like a shipment identifier) is to export your custom schema or helper function and import it wherever needed. For example: // shared-schemas.ts
import { z } from "zod";
export const shippingIdSchema = () =>
z.string().regex(/^SHIP-\d{6}$/, { message: "Invalid shipment ID" });
// usage
import { shippingIdSchema } from "@lib/shared-schemas";
import { z } from "zod";
const schema = z.object({
shipmentIdentifier: shippingIdSchema(),
});If you want a more ergonomic API (like // custom-zod.ts
export * from "zod";
export const shippingId = () =>
z.string().regex(/^SHIP-\d{6}$/, { message: "Invalid shipment ID" });
// usage
import * as z from "./custom-zod";
const schema = z.object({
shipmentIdentifier: z.shippingId(),
});This pattern gives you the API you want, but you must import from your custom module instead of the original Zod package. Community packages like If this answers your question, please close the issue! If you need a more tailored example, let me know. To reply, just mention @dosu. How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Is there anyway to extend the built-in validations like
z.string()with my own shared validations?For example, we have specific validation for shipment indentifiers. I would love if we could, across our entire application just use the following:
I think the only way to do this is to export the schema as an object:
I've tried the approaches in this discussion:
#2616
But all fail due to issues overriding the
znamespace properly.Beta Was this translation helpful? Give feedback.
All reactions