Zod is a powerful TypeScript-first schema declaration and validation library that allows developers to define the structure of their data and ensure it conforms to specified types. Among its many features, parse
safeParse
parse
safeParse
parse
The parse
const parsedValue = schema.parse(input);
If the
input
parse
parse
import { z } from 'zod'; // Define a simple schema const userSchema = z.object({ name: z.string(), age: z.number().min(18) }); // Valid input const validInput = { name: 'Alice', age: 30 }; const parsedUser = userSchema.parse(validInput); console.log(parsedUser); // { name: 'Alice', age: 30 } // Invalid input const invalidInput = { name: 'Bob', age: 17 }; try { userSchema.parse(invalidInput); } catch (e) { console.error(e.errors); // Outputs validation errors }
In the example above, parse
When using parse
import { z } from 'zod'; const productSchema = z.object({ title: z.string(), price: z.number().positive(), }); const productInput = { title: 'Laptop', price: -1500, // Invalid price }; try { productSchema.parse(productInput); } catch (error) { if (error instanceof z.ZodError) { console.error('Validation errors:', error.errors); } }
In this example, the validation fails because the price is negative. The error handling logic checks if the error is an instance of z.ZodError
safeParse
The safeParse
parse
safeParse
The syntax for safeParse
const result = schema.safeParse(input);
The returned
result
success
data
error
safeParse
import { z } from 'zod'; const userSchema = z.object({ name: z.string(), age: z.number().min(18) }); const input = { name: 'Charlie', age: 17 }; const result = userSchema.safeParse(input); if (result.success) { console.log('Parsed user:', result.data); } else { console.error('Validation errors:', result.error.errors); }
In this example, the safeParse
parse
and safeParse
The choice between parse
safeParse
parse
safeParse
Let’s delve deeper into more complex use cases for both parse
safeParse
Zod supports nested objects, which can be validated using both methods.
const addressSchema = z.object({ street: z.string(), city: z.string(), postalCode: z.string().length(5), }); const userSchema = z.object({ name: z.string(), age: z.number().min(18), address: addressSchema, }); const userInput = { name: 'Eve', age: 25, address: { street: '123 Main St', city: 'Springfield', postalCode: '12345' } }; const result = userSchema.safeParse(userInput); if (result.success) { console.log('Valid user data:', result.data); } else { console.error('Validation errors:', result.error.errors); }
In this example, both the user and address are validated, showcasing how Zod can handle complex structures effectively.
Sometimes, you may need to perform asynchronous checks, such as checking if an email already exists in a database. Zod allows asynchronous transformations with the refine
safeParse
const emailSchema = z.string().email().refine(async (email) => { const exists = await checkEmailInDatabase(email); // hypothetical async function return !exists; }, { message: "Email already exists", }); const result = await emailSchema.safeParseAsync('test@example.com'); if (result.success) { console.log('Valid email:', result.data); } else { console.error('Validation errors:', result.error.errors); }
In this example, we validate an email and ensure it does not already exist in a database, using safeParseAsync
When using Zod for validation, performance is generally efficient. However, in scenarios with large data structures or high-frequency validation calls, it is crucial to evaluate the impact on performance. Use the following strategies:
safeParse
Here are some common pitfalls to avoid when using parse
safeParse
safeParse
The parse
safeParse
simplify and inspire technology
©2024, basicutils.com