Skip to content

Use zod for validation #16

@MikeCarbone

Description

@MikeCarbone

No use in rolling our own validation lib. We can extend the zod library checks to use custom ones if we cant find one that fits our need. Otherwise, like emails and phone numbers, we should use zod's shape so we can better utilize it. Less work for us.

Under the hood, zod's validations look like this:

[
	{ kind: "url" },
	{
		kind: "min",
		value: 5,
		message: "Must be 5 or more characters long",
	},
	{
		kind: "startsWith",
		value: "https://",
		message: "Must provide secure URL",
	},
]

Bring in what we need:

import { z } from "zod";
import { type Fields } from "@interweave/interweave";

Using Interweave's Fields type:

const fields: Fields = {
	url: {
		schema: {
			type: "string",
		},
	},
};

We can then:

function interweaveToZod(field: any) {
	// @ts-expect-error
	let zod = z[field.schema.type]();
	checks.forEach((c) => {
		zod = zod[c.kind](c.value, { message: c.message });
	});
	return zod;
}

const username = interweaveToZod(fields.url);
const parse = username.safeParse("test");

That function above will essentially map an Interweave field to a zod validation pattern. Don't know what the final integration would look like, but all of this to say: it's possible!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions