Using Enum in Zod Validation
When working with TypeScript, it’s common to use libraries like Zod for data validation. Zod provides a simple and intuitive way to define schemas and validate data against them. However, using enums in Zod validation can be a bit tricky. In this blog post, we will explore different solutions to effectively use enums in Zod validation.
Solution 1: Using the “literal” method
One way to use enums in Zod validation is by using the “literal” method. The “literal” method allows you to specify a specific value that the validated data must match exactly. Here’s an example:
import { z } from "zod";
enum UserRole {
Admin = "admin",
User = "user",
}
const userSchema = z.object({
role: z.literal(UserRole.Admin),
});
const userData = {
role: "admin",
};
const validationResult = userSchema.safeParse(userData);
console.log(validationResult.success); // true
In the above example, we define an enum called “UserRole” with two possible values: “Admin” and “User”. We then create a Zod schema using the “object” method and specify that the “role” field must be a literal value of “UserRole.Admin”. Finally, we validate the “userData” object and check if the validation was successful.
Solution 2: Using the “enum” method
Another way to use enums in Zod validation is by using the “enum” method. The “enum” method allows you to specify an array of possible values that the validated data can match. Here’s an example:
import { z } from "zod";
enum UserRole {
Admin = "admin",
User = "user",
}
const userSchema = z.object({
role: z.enum([UserRole.Admin, UserRole.User]),
});
const userData = {
role: "admin",
};
const validationResult = userSchema.safeParse(userData);
console.log(validationResult.success); // true
In this example, we define the same “UserRole” enum as before. However, this time we use the “enum” method in the Zod schema to specify that the “role” field can be either “UserRole.Admin” or “UserRole.User”. The rest of the code is similar to the previous solution.
Conclusion
Using enums in Zod validation is possible by either using the “literal” method or the “enum” method. The choice between the two methods depends on your specific use case and preference. Both methods provide a straightforward way to validate enum values in TypeScript using Zod.
Remember to always choose the method that best suits your needs and follow the Zod documentation for more advanced validation scenarios.
Leave a Reply