In a React application, every form is an essential part. The application needs to make sure that the users are entering valid information before submitting, whether we are building a login page, registration form, contact form, checkout page, etc. We can write all the validation checks and logic of the forms ourselves manually in the application, but when our application grows, these validations and logic can quickly become very difficult to manage. This is where the Zod package comes in.
The Zod package is a TypeScript-first schema validation library that will make the handling of form validation simple, readable, and reusable. So instead of writing multiple validation checks throughout the React components, we can define a validation rule in one place and let the Zod package handle the rest of the work. In this blog, we can learn how to install and use Zod. We will create a validation schema, validate a form with Zod, handle validation errors, and display validation error messages in the UI of the application.
Install Zod
Firstly, we will install the Zod package in our project.
npm install zod
Create Your First Validation Schema
Now, Let’s create a validation schema for our simple registration form. In the form, we will ask the user for their name, email, and password. Then, we can create the form schema.
import { z } from "zod";
const formSchema = z.object({
name: z.string().min(1, "Name is required"),
email: z.email("Enter a valid email"),
password: z.string().min(8, "Password must be at least 8 characters"),
});Validate the Form Data
Let's suppose our form data looks like this.
const formData = {
name: "John",
email: "john@example.com",
password: "password123",
};We can validate it using the safeParse() method.
const result = formSchema.safeParse(formData);
if (!result.success) {
console.log(result.error.issues);
} else {
console.log(result.data);
}If the data is valid, we can safely submit it. If the data is not valid, Zod provides the detailed validation errors.
Display Validation Errors
Each validation error includes useful information like the field that failed, the validation message, and the reason it failed.
For example:
[
{
origin: "string",
code: "invalid_format",
format: "email",
path: ["email"],
message: "Enter a valid email",
},
];
We can display these messages next to our form fields to help users correct their inputs.
Common Validation Rules
Zod has many built-in validation methods.
Required Fields
z.string().min(1, "Required")
Email Validation
z.email("Invalid email")Minimum Length
z.string().min(8)
Maximum Length
z.string().max(30)
Numbers
z.number().min(18)
Optional Fields
z.string().optional()
Validate Matching Passwords
Many validation forms ask users to confirm their passwords. We can check that both passwords match by using the refine() method.
const schema = z
.object({
password: z.string().min(8),
confirmPassword: z.string()
})
.refine((data) => data.password === data.confirmPassword, {
message: "Passwords do not match",
path: ["confirmPassword"],
});
Form validation is an important part of building a reliable and secure React application. It helps users to catch all the mistakes before submitting a form and also ensures the application receives the data it expects. Zod package makes the validation process simple with the help of easy-to-read schemas and easy to maintain codes.
To read more about How to Add Google Places Autocomplete to a React App, refer to our blog How to Add Google Places Autocomplete to a React App.