Blog>
Snippets

Creating and Validating a Schema with Zod

Showcase creating a simple schema with Zod for validating a user registration form - including name, email, and password fields.
import { z } from 'zod';
First, import the Zod library to use for schema creation and validation.
const RegistrationSchema = z.object({
  name: z.string().min(1, 'Name is required'),
  email: z.string().email('Invalid email format'),
  password: z.string().min(8, 'Password must be at least 8 characters')
});
Create a schema for user registration. This schema defines the structure and rules for valid inputs: name must not be empty, email must be in a valid format, and password must have at least 8 characters.
const userData = {
  name: 'John Doe',
  email: 'john@example.com',
  password: 'securepassword'
};
Define a sample user data object to validate against the registration schema. This includes a name, email, and password.
const validationResult = RegistrationSchema.safeParse(userData);
Validate the user data against the registration schema. The `safeParse` method is used to safely validate the data, returning a result object that indicates whether the validation was successful and contains any errors.
if (validationResult.success) {
  console.log('User data is valid');
} else {
  console.log('Validation errors:', validationResult.error.issues);
}
Check the result of the validation. If successful, log a message indicating the data is valid. If not, log the validation errors.