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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

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

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay