logo
Basic Utils
Home

Using the refine Method in Zod

Table of Contents

Introduction

The refine method in Zod allows you to apply custom validation logic to a schema. While Zod provides built-in methods for most common validations, such as string length or numeric ranges, refine is useful when you need to validate a schema in ways not covered by the built-in methods. The refine method takes a predicate (a function that returns true or false) and uses it to determine if the schema passes validation.

Basic Usage of refine

Here is a simple example of using refine to validate that a number is even:


// Basic Zod refine usage
const evenNumberSchema = z.number().refine(val => val % 2 === 0, {
    message: "The number must be even."
});

evenNumberSchema.safeParse(4); // passes
evenNumberSchema.safeParse(3); // fails with message "The number must be even."

Custom Error Messages with refine

One of the advantages of refine is that you can pass a custom error message to provide more specific feedback. In the example above, we specify the message "The number must be even." to indicate why the validation failed. Without specifying a message, Zod will use a generic error response.

Refining Complex Schemas

The refine method can be used on any type of Zod schema, including objects and arrays. For example, here’s how you can use refine to ensure that two fields in an object schema match:


// Refining a complex object schema
const passwordSchema = z.object({
    password: z.string(),
    confirmPassword: z.string()
}).refine(data => data.password === data.confirmPassword, {
    message: "Passwords must match.",
    path: ["confirmPassword"] // Pointing the error to a specific field
});

passwordSchema.safeParse({ password: "secret", confirmPassword: "secret" }); // passes
passwordSchema.safeParse({ password: "secret", confirmPassword: "different" }); // fails with message "Passwords must match."

Difference Between refine and Other Methods

While Zod provides other methods like superRefine and transform, refine is the go-to method for simple validations that can be reduced to a boolean check. Use superRefine for cases where you need to report multiple errors or provide context-specific information. Transform, on the other hand, is used to modify the input data rather than to validate it.

Conclusion

The refine method is a powerful tool when working with custom validations in Zod. It allows you to go beyond the built-in methods and handle more specific or complex validation cases. By providing the ability to pass custom error messages and paths, refine ensures that your validation feedback is clear and precise.

logo
Basic Utils

simplify and inspire technology

©2024, basicutils.com