Custom Validation
on this page
Zod's Built-In Constraints
Zod offers a range of built-in constraints that you can apply to its primitive types. These constraints help you define and validate your data schemas effectively. Here are some commonly used constraints, but for a comprehensive list, please refer to the documentation.
String Constraints
- z.string().max(5): Limits the maximum length of a string to 5 characters.
- z.string().min(5): Requires the minimum length of a string to be 5 characters.
- z.string().length(5): Ensures that a string has exactly 5 characters.
- z.string().email(): Validates that a string is in an email format.
- z.string().url(): Validates that a string is a URL.
- z.string().ip(): Validates that a string is an IP address.
- z.string().regex(regex): Applies a custom regular expression for string validation.
Number Constraints
- z.number().gt(5): Ensures that a number is greater than 5.
- z.number().gte(5): Requires a number to be greater than or equal to 5 (alias for .min(5)).
- z.number().lt(5): Requires a number to be less than 5.
- z.number().lte(5): Ensures that a number is less than or equal to 5 (alias for .max(5)).
- z.number().int(): Validates that a value is an integer.
Date Constraints
- z.date().min(new Date("1900-01-01")): Validates that a date is not earlier than January 1, 1900.
- z.date().max(new Date()): Ensures that a date is not in the future.
Implementing Custom Validation Logic
Sometimes, your validation requirements may not fit the predefined constraints. In such cases, Zod offers the refine method, allowing you to implement custom validation logic.
Example: Validating Palindromes
Suppose you need to validate whether a string is a palindrome. First, create a simple function that checks if a string is a palindrome:
function IsPalindrome(input : string){
const reverse = [...input].reverse().join('');
return input === reverse;
}
Now, we can use the refine method to apply this custom validation logic to our Zod schema:
const palindromeValidator = z.string().min(1).refine(IsPalindrome);
With this approach, you can extend Zod's validation capabilities to match your specific requirements.