乐闻世界logo
搜索文章和话题

How to validate a string literal type using zod

1个答案

1

When using Zod for data validation, validating string literal types (also known as literal types) is a common requirement. String literal types refer to specific string values. In Zod, you can use z.literal to define and validate specific string values.

How to Use z.literal for Validation

First, install the Zod library if you haven't already. Use the following command:

bash
npm install zod

Next, create a simple validation schema to verify if a variable matches the specified string literal. Here's a specific example:

javascript
import { z } from 'zod'; // Define a Zod schema that only accepts the string 'admin' as valid input const AdminRole = z.literal('admin'); // Use this schema to validate data try { AdminRole.parse('admin'); // valid because it matches 'admin' console.log('Validation passed!'); } catch (error) { console.error('Validation failed:', error); } try { AdminRole.parse('user'); // invalid because it doesn't match 'admin' } catch (error) { console.error('Validation failed:', error); }

Extended Use Case: Handling Multiple String Literals with z.union

If you need to validate one of several fixed strings, use z.union to combine multiple z.literal definitions:

javascript
import { z } from 'zod'; // Define a schema that accepts 'admin', 'user', or 'guest' as valid inputs const UserRole = z.union([z.literal('admin'), z.literal('user'), z.literal('guest')]); // Validate data try { UserRole.parse('user'); // valid console.log('Validation passed!'); } catch (error) { console.error('Validation failed:', error); } try { UserRole.parse('manager'); // invalid } catch (error) { console.error('Validation failed:', error); }

Summary

Using z.literal and z.union can effectively define validation rules for specific string values or a set of specific string values. This method is highly useful for handling configuration items, permission roles, and similar scenarios, ensuring data accuracy and application stability.

2024年7月21日 19:47 回复

你的答案