A package that I'd like to share with you today is truly a must have, expecially for server side validation! It's called zod and it allows you to create schemas for you data and not only validate it, but also ensure it has correct types.
You can install it with e.g. deno add npm:zod
(or import directly from https://deno.land/x/zod/mod.ts
) and use like so:
// main.ts
import { z } from "https://deno.land/x/zod/mod.ts";
const Message = z.object({
message: z.string().min(1),
urgency: z.number({ coerce: true }).int().min(1).max(3).optional(),
});
console.log(Message.parse({ message: "Hello!", urgency: "2" }));
console.log(Message.parse({ message: "" }));
And running it with e.g. deno run -A main.ts
should result in:
deno run -A ./main.ts
{ message: "Hello!", urgency: 2 }
error: Uncaught (in promise) ZodError: [
{
"code": "too_small",
"minimum": 1,
"type": "string",
"inclusive": true,
"exact": false,
"message": "String must contain at least 1 character(s)",
"path": [
"message"
]
}
]
And as a nice addition to clean and verified data you get it neatly typed:
Liked the content and would love to have more of it all year long?
Top comments (0)