1.Validate a sign-up form with Zod
IntermediateWrite a Zod schema for a sign-up with name (trimmed, 2 to 50 characters), email (a valid email) and age (an integer of at least 13). Validate { name: " Kiran ", email: "kiran@example.com", age: 21 } and { name: "K", email: "kiran@", age: 12.5 }, printing the cleaned data or each error as field: message.
Show hint
z.object({ name: z.string().trim().min(2).max(50), email: z.email(), age: z.number().int().min(13) }) and safeParse.
Show solution
import { z } from "zod";
const Signup = z.object({
name: z.string().trim().min(2).max(50),
email: z.email(),
age: z.number().int().min(13),
});
for (const input of [{ name: " Kiran ", email: "kiran@example.com", age: 21 }, { name: "K", email: "kiran@", age: 12.5 }]) {
const result = Signup.safeParse(input);
if (result.success) console.log("OK:", result.data);
else for (const issue of result.error.issues) console.log(`${issue.path.join(".")}: ${issue.message}`);
}OK: { name: 'Kiran', email: 'kiran@example.com', age: 21 }
name: Too small: expected string to have >=2 characters
email: Invalid email address
age: Invalid input: expected int, received number