Extending Zod Schema with Custom Validation Rules
Q: How would you extend a Zod schema to include a custom validation rule?
- Zod
- Junior level question
Explore all the latest Zod interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Zod interview for FREE!
To extend a Zod schema with a custom validation rule, you can use the `.refine()` method. This method allows you to define a custom validation function that can perform complex validation logic.
For example, suppose we have a schema for a user object where we want to validate that the password contains at least one uppercase letter and one digit. Here’s how we can extend the schema with a custom validation rule:
```javascript
import { z } from 'zod';
const userSchema = z.object({
username: z.string().min(3),
password: z.string().min(8).refine((value) => {
const hasUppercase = /[A-Z]/.test(value);
const hasDigit = /\d/.test(value);
return hasUppercase && hasDigit;
}, {
message: "Password must contain at least one uppercase letter and one digit",
}),
});
// Example usage:
try {
userSchema.parse({
username: 'john_doe',
password: 'Password1',
});
console.log("Validation succeeded");
} catch (e) {
console.error(e.errors);
}
```
In this example, the custom validation checks for at least one uppercase letter and one digit in the password. If the password doesn’t meet these criteria, the validation will fail and return the specified error message.
This approach allows us to incorporate complex, domain-specific validations while still leveraging the power of Zod's schema validation capabilities.
For example, suppose we have a schema for a user object where we want to validate that the password contains at least one uppercase letter and one digit. Here’s how we can extend the schema with a custom validation rule:
```javascript
import { z } from 'zod';
const userSchema = z.object({
username: z.string().min(3),
password: z.string().min(8).refine((value) => {
const hasUppercase = /[A-Z]/.test(value);
const hasDigit = /\d/.test(value);
return hasUppercase && hasDigit;
}, {
message: "Password must contain at least one uppercase letter and one digit",
}),
});
// Example usage:
try {
userSchema.parse({
username: 'john_doe',
password: 'Password1',
});
console.log("Validation succeeded");
} catch (e) {
console.error(e.errors);
}
```
In this example, the custom validation checks for at least one uppercase letter and one digit in the password. If the password doesn’t meet these criteria, the validation will fail and return the specified error message.
This approach allows us to incorporate complex, domain-specific validations while still leveraging the power of Zod's schema validation capabilities.


