Zod** is a fictional character in the DC Extended Universe. Zod is a TypeScript-first validation library, you can define schema to validate the data. This plugin save me a lot from creating a ton of validation into few lines only.
History & Implementation
When I develop a site, I need to create a validation form with certain rules & data to handle, so I need a lot of validation on my site. I create a lot of code or rules with a lot of custom messages and logic. But I think this is a bad idea if the rules are getting bigger and bigger. So I decided to do some research then.
During that time, I did some research & found this plugin, Zod helped me a lot of times & lines. Why? Because of this:
Native rules Javascript.
function validatePassword(password) {
const minLength = 6;
const maxLength = 150;
if (typeof password !== "string") {
return { valid: false, message: "Password must be a string." };
}
if (password.length < minLength) {
return {
valid: false,
message: `Password must be at least ${minLength} characters.`,
};
}
if (password.length > maxLength) {
return {
valid: false,
message: `Password must be no more than ${maxLength} characters.`,
};
}
if (!/[A-Z]/.test(password)) {
return {
valid: false,
message: "Password must contain at least one uppercase letter.",
};
}
if (!/[a-z]/.test(password)) {
return {
valid: false,
message: "Password must contain at least one lowercase letter.",
};
}
if (!/\d/.test(password)) {
return {
valid: false,
message: "Password must contain at least one number.",
};
}
if (!/[^A-Za-z0-9]/.test(password)) {
return {
valid: false,
message: "Password must contain at least one special character.",
};
}
return { valid: true, message: "Valid password." };
}
You will write a long script & logic to handle password validation.
But if we are using Zod, script will look like this:
import { z } from "zod";
const passwordSchema = z
.string()
.min(6, { message: "Password must be at least 6 characters." })
.max(150, { message: "Password must be no more than 150 characters." })
.refine((val) => /[A-Z]/.test(val), {
message: "Password must contain at least one uppercase letter.",
})
.refine((val) => /[a-z]/.test(val), {
message: "Password must contain at least one lowercase letter.",
})
.refine((val) => /\d/.test(val), {
message: "Password must contain at least one number.",
})
.refine((val) => /[^A-Za-z0-9]/.test(val), {
message: "Password must contain at least one special character.",
});
More simple, clean & easier to maintain.
Conclusion
Zod transforms complex validation logic into clean, maintainable code. Instead of writing dozens of lines with custom validation functions and error handling, you can define schemas in just a few lines.
Zod saves your time, effort, and countless lines of code.
For more detail information you can read completely on Zod documentation.