DEV Community

Cover image for Day 7: Your input is valid πŸ–οΈ
Valeria
Valeria

Posted on

2

Day 7: Your input is valid πŸ–οΈ

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: "" }));
Enter fullscreen mode Exit fullscreen mode

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"
    ]
  }
]
Enter fullscreen mode Exit fullscreen mode

And as a nice addition to clean and verified data you get it neatly typed:

Message type includes string

Liked the content and would love to have more of it all year long?

Buy Me A Coffee

Image of Timescale

πŸš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsβ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post β†’

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay