Limited Period Offer : 20% Discount on online/offline courses, for more details call/whatsapp

Establishing Validation by Converting TypeScript Code to Zod Schemas

0 min read
1 year ago By Mitali Gupta
Establishing Validation by Converting TypeScript Code to Zod Schemas

Data validation plays a crucial role in software development to ensure data integrity and prevent errors. In this article, we will explore the process of converting TypeScript code to Zod schemas to establish effective data validation. By leveraging Zod's powerful validation capabilities.

  • Install Zod:
  npm install zod

or

  yarn add zod
  • .Import zod :
import { z } from 'zod';
  • Convert TypeScript Types to Zod Schemas:
import * as z from 'zod';

type Status = 'active' | 'inactive';

const statusSchema = z.union([z.literal('active'), z.literal('inactive')]);
//  Typescript type
interface User {
  name: string;
  age: number;
  status: Status;
  email?: string;
}

// Zod Schema
const userSchema = z.object({
  name: z.string(),
  age: z.number(),
  status: statusSchema,
  email: z.string().optional(),
});

  • Define Validation Rules:
import * as z from 'zod';

const statusSchema = z.union([z.literal('active'), z.literal('inactive')]);

const userSchema = z.object({
  name: z.string(),
  age: z.number(),
  status: statusSchema,
  email: z.string().optional(),
});
  • Validate data :
const userData = {
  name: 'Mohan',
  age: 25,
  status: 'active',
  email: 'mohan@example.com',
};

try {
  const validatedData = userSchema.parse(userData);
  console.log(validatedData); // Validated data
} catch (error) {
  if (error instanceof z.ZodError) {
    console.error(error.errors); // Validation errors
  } else {
    console.error('An error occurred during validation.');
  }
}


Jun 21, 2023 12:00 Back to Articles

Other Articles

Introducing ECMAScript 6 (ES6): A New Era for JavaScript Development Introducing ECMAScript 6 (ES6): A New Era for JavaScript Development

In this article, we'll explore the important changes and improvements that came with ECMAScript 6 (ES6), and how they've made JavaScript programming better.

1 year ago By Mitali Gupta
How to use and upload profile photos to AWS s3 using laravel jetstream

Using jetsream to upload photos to s3 configuration and details

1 year ago By Santosh Kshirsagar
For Laravel Setting UP CI/CD Pipeline using GitHub, CodeDeploy, S3 and EC2

Setting ci/cd pipeline for laravel application on aws using github actions then uploading to s3 and using codedeploy application gets installled on EC2 instance

1 year ago By Santosh Kshirsagar
Level Order Traversal in Binary Tree

In a Binary Tree the level order traversal is used to traverse all the elements of binary tree by starting from root to traversing all nodes of one level before moving to other level.

1 year ago By Aniket Prajapati