Mastering ZOD for validation in Nextjs

Mastering ZOD for validation in Nextjs

Introduction to the Project

Welcome and Overview

  • The speaker welcomes viewers to the "Chai and Code" series, introducing the third project focused on production-level development.
  • The target for comments is set at 530, emphasizing their importance for motivation and engagement in the project.

Project Details

  • The video will cover creating a simple Next.js project and discuss libraries, particularly focusing on Zod for schema validation.
  • While Mongoose will also be used, there will be a discussion on why Zod is preferred for certain aspects of schema management.

Project Setup

Initial Steps

  • The project is named "Mystery Message," with adjustments made to avoid conflicts with existing repositories.
  • TypeScript will be utilized throughout the project, providing type safety while remaining similar to JavaScript.

Tools and Libraries

  • Linting tools and Tailwind CSS will be integrated into the workflow; Zod will serve as a library for validation purposes.
  • A source directory structure is preferred for better organization within the project.

Installation Process

Running Commands

  • The speaker discusses potential issues during installation due to CPU usage while recording videos, which may slow down processes.
  • After navigating to the app directory, they open Visual Studio Code (VS Code), preparing to run initial commands.

Troubleshooting

  • If issues arise when starting the application, it’s recommended to check installations or rerun npm install before executing npm run start.

Application Structure

Creating Models

  • Emphasis is placed on modeling data correctly before proceeding with application development; this includes defining how data will be stored in databases.
  • A new folder named "models" is created within the source directory to organize all models related to user data effectively.

Using Mongoose

  • Mongoose is introduced as an ORM that simplifies interactions with MongoDB by acting as an intermediary layer between applications and databases.

Installation and Setup of Mongoose with TypeScript

Initial Setup

  • The speaker discusses the installation process for Mongoose, noting that it may require additional types for TypeScript.
  • Emphasizes the need to import both Mongoose and Schema, as well as Document for type safety in TypeScript.

Defining Data Types

  • Introduces the concept of defining data types using interfaces in TypeScript, which is a common practice.
  • Explains how to define a message format, specifying that content will be a string type and created date will be in date format.

Creating Message Schema

  • Discusses exporting an interface named "MessageSchema" to represent the structure of messages stored in MongoDB.
  • Highlights the importance of extending Document from Mongoose to ensure proper document structure within MongoDB.

Implementing Type Safety

  • The speaker notes that once you learn this syntax, it can be reused across different schemas easily.
  • Mentions that since they are using TypeScript, they must adhere to the defined message interface when creating schemas.

Finalizing Message Schema Structure

  • Describes how to specify data types within the schema using diamond brackets for custom schemas.
  • Clarifies that while defining fields like content, it's crucial to remember case sensitivity between Mongoose's string type (capitalized) and TypeScript's string type (lowercase).

Defining User Schema

User Schema Creation

  • The speaker transitions into defining a user schema by copying and modifying the existing message schema.

Specifying User Fields

  • Lists required fields for user schema: username (string), email (string), password (string), and verification code (string).

User Document Structure and Validation

User Verification Code Management

  • The verification code's expiration must be tracked to ensure users are aware of its validity period. A date format will be used for this purpose.
  • Each message from the user will create a separate document, which will also be stored within the user's profile as a special type of array rather than a standard one.

Schema Creation for User Data

  • The interface for the user schema has been established, and it is essential to replicate this structure in the schema creation process.
  • The user schema should follow specific guidelines, ensuring all necessary fields are included systematically.

Field Requirements and Custom Messages

  • Required fields such as username must have validation messages; if not provided, custom error messages can inform users accordingly.
  • Additional validations include trimming spaces from usernames and ensuring they are unique within the application context.

Email Validation Techniques

  • Email addresses must also be validated with similar requirements as usernames, including uniqueness and required status.
  • Regular expressions (regex) can be utilized for email validation; resources like ChatGPT or regex websites can assist in generating appropriate patterns.

Password and Verification Code Fields

  • A password field is required alongside a verification code field, both marked as mandatory inputs in the schema.
  • The verification code should also have an expiration date associated with it to maintain security protocols.

User Status Indicators

  • An "is verified" boolean field will indicate whether a user has completed verification; defaults may be set to false unless specified otherwise.
  • Another boolean field "is accepting messages" allows users to opt-in for receiving communications, defaulting to true.

This structured approach ensures that all aspects of user data management are covered comprehensively while maintaining clarity on each requirement.

Last Field Schema and Message Types

Overview of Message Types

  • The discussion begins with the completion of the last field schema, emphasizing that messages are essentially documents themselves.
  • It is suggested to directly write arrays for message types instead of complicating the structure, especially when dealing with custom data types.

Exporting Data in Next.js

  • The speaker transitions to how to export data within a Next.js application, noting that most applications run on edge time. This means the source code runs continuously rather than starting anew each time.
  • A dedicated backend using Express is mentioned as a common approach, where once initialized, it continues running without restarting.

Handling User Models

  • When exporting user models in Next.js, there’s a need to check if they already exist; if not, create them through MongoDB and return the result. This dual-check process is crucial for ensuring data integrity.
  • The speaker emphasizes checking both cases: whether a model exists or needs creation before proceeding with operations.

Utilizing Mongoose for Model Definitions

  • Mongoose is introduced as a tool for defining models; specifically mentioning how to reference user schemas correctly while ensuring type safety through TypeScript integration.
  • There’s an explanation about importing Mongoose at the top of files and specifying that the expected return type should match the defined user model type in TypeScript.

Type Safety and Schema Creation

  • The importance of type safety in TypeScript is highlighted; even though it may seem complex initially, it provides significant benefits in preventing errors during development. Users are encouraged to gradually familiarize themselves with these concepts.
  • The speaker notes that while creating schemas might seem redundant since they have been defined earlier, they serve different purposes when used within MongoDB versus other contexts like validation during signup processes.

Creating Validation Schemas

Importance of Validation

  • As part of building out schemas for various functionalities (like sign-up), validation becomes essential to ensure correct data input from users (e.g., checking username formats).
  • A library called "Joi" will be utilized for validation purposes; its documentation will be reviewed later in detail but initial setup requires multiple files corresponding to different entities needing validation checks.

User Signup and Validation Process

Overview of User Signup

  • The user begins the process by signing up, which is followed by a verification step. A schema for verification is established to ensure that the code sent (e.g., six or eight digits) adheres to specific validation rules.
  • After signup and verification, the user proceeds to sign in. The sign-in schema includes an acceptance message, which primarily consists of a boolean value indicating success.

Message Schema and Validation

  • The message schema must also be defined clearly; it plays a crucial role in understanding validation processes rather than just database structure.
  • To facilitate this process, a library called "Zod" is introduced. This library is popular for its utility in schema validation within TypeScript applications.

Introduction to Zod Library

Features of Zod

  • Zod is recognized as one of the most popular libraries due to its high weekly downloads, indicating widespread use in production environments.
  • It specializes in type-safe schema validation, allowing developers to validate various data types such as emails without needing extensive manual checks.

Usage and Documentation

  • Basic usage involves importing Zod and creating object schemas for different entities like users or messages. Developers can define properties using methods provided by Zod.
  • For instance, validating a username can be done using z.string(), with additional methods available for further constraints like minimum or maximum length.

Implementing User Signup Validation

Steps for Validation

  • When implementing user signup, two main fields are validated: username and email/password. The initial step involves checking if these fields meet specified criteria.
  • The validation logic allows exporting so that it can be reused across different parts of the application.

Detailed Checks on Username

  • Username validation starts with checking if it's a string. Additional checks include ensuring it meets minimum character requirements (e.g., at least two characters).
  • Maximum character limits can also be enforced (e.g., no more than 20 characters), providing clear error messages when validations fail.

Advanced Validations

  • Further down the line, regex patterns can be applied for more complex validations such as special character checks, enhancing input security and integrity during signup processes.

User Name Validation and Sign-Up Schema Implementation

Regular Expression for User Name Validation

  • The user name must not contain special characters, only allowing alphanumeric characters and underscores. This is established using a simple regex pattern.
  • A basic regex was created through ChatGPT to validate the user name, focusing on ensuring it contains only characters from 0-9 and a-j (both lower and upper case).

Sign-Up Schema Development

  • The sign-up schema is built similarly to the user name validation, utilizing the same syntax for consistency. It involves exporting constants and defining an object structure.
  • An object is created to check multiple fields: user name, email, and password validations are all included in this schema setup.

Email Validation Process

  • Email validation checks if the input is a string and conforms to standard email formats; an error message "Invalid email address" can be returned if validation fails.
  • The process simplifies previous methods by automatically handling common checks without needing extensive regex patterns as seen in earlier implementations.

Password Requirements

  • Password validation requires a minimum of six characters but can be adjusted based on specific needs (e.g., eight or ten characters). Messages indicating requirements are also included for clarity during input errors.
  • The password field will also validate that it meets length requirements while providing feedback messages like "Password must be at least six characters." This ensures users understand their input requirements clearly.

Verification Schema Setup

  • A verification schema is introduced that checks if inputs are strings with a minimum character count of six for passwords, ensuring basic security measures are met before processing further actions like sign-in attempts.
  • The implementation allows flexibility in naming conventions (e.g., using either 'identifier' or 'user name') while maintaining simplicity in required fields such as password during sign-in processes.

Message Schema Configuration

  • For messaging functionality within the application, content length must meet a minimum requirement of ten characters to ensure meaningful communication between users; this prevents empty or overly brief messages from being sent.

User Sign-Up and Schema Validation

Overview of User Input Limitations

  • The discussion begins with the implementation of a maximum character limit for user input, specifically set to 300 characters. This is crucial for ensuring data integrity during sign-up processes.

Adjustments in Sign-In Schema

  • A need for modification in the sign-in schema is identified, particularly regarding the acceptance message. The speaker emphasizes the importance of maintaining accurate schemas throughout the application.

User Sign-Up Process Details

  • During user sign-up, two key validations are performed: username validation and email/password verification. A six-digit code is sent for identification purposes, ensuring secure access.

Message Schema Specifications

  • The message schema requires content to be a string between 10 to 300 characters. This specification is part of defining the overall architecture and functionality of the application.

Next Steps in Configuration

  • The speaker indicates that further configuration tasks will be addressed in subsequent videos, highlighting ongoing development efforts and encouraging viewers to stay engaged with future content.
Video description

Welcome to chai aur code, a coding/programming dedicated channel in Hindi language. Now you can learn best of programming concepts with industry standard practical guide in Hindi language. I have released the source code here :https://github.com/hiteshchoudhary/ama-app For more info, visit, https://chaicode.com All source code is available at my Github account: https://github.com/hiteshchoudhary Our Open-Source Project is here: https://freeapi.app Join me at whatsapp: https://hitesh.ai/whatsapp for community discord: https://hitesh.ai/discord Instagram pe yaha paaye jaate h: https://www.instagram.com/hiteshchoudharyofficial/ HTML video series: https://www.youtube.com/watch?v=XmLOwJHFHf0&list=PLu71SKxNbfoDBNF5s-WH6aLbthSEIMhMI Complete javascript series: https://www.youtube.com/watch?v=Hr5iLG7sUa0&list=PLu71SKxNbfoBuX3f4EOACle2y-tRC5Q37 Complete Reactjs series: https://www.youtube.com/watch?v=vz1RlUyrc3w&list=PLu71SKxNbfoDqgPchmvIsL4hTnJIrtige Javascript and react interview series: https://www.youtube.com/watch?v=1wqCyz7XrV4&list=PLu71SKxNbfoCy_MsA98SBfvUKF5eQit6L Backend development with Javascript: https://www.youtube.com/watch?v=EH3vGeqeIAo&list=PLu71SKxNbfoBGh_8p_NS-ZAh6v7HhYqHW Python Series: https://www.youtube.com/watch?v=Ca5DLSDfPec&list=PLu71SKxNbfoBsMugTFALhdLlZ5VOqCg2s