[Typescript] Zod custom error message


const BookingSchema = z.object({
  roomType: z.string(),  
  dueDate: z
    .string({
      message: "invalid due date",
    })
    .date('date format is wrong'),
  numberOfGuests: z
    .number()
    .min(1, "there must be at least one guest")
    .max(4, "at most 4 guests are allowed"),
  price: z.number().positive("negative price, huh?"),
});

type Booking = z.infer<typeof BookingSchema>;

const validBooking: Booking = {
  roomType: "suite",
  dueDate: "2025-12-31",
  numberOfGuests: 3,
  price: 300,
};

try {
  // BookingSchema.parse({ ...validBooking, numberOfGuests: 0 });
  // BookingSchema.parse({ ...validBooking, price: -100 });
  BookingSchema.parse({ ...validBooking, dueDate: "-100" });
} catch (e) {
  if (e instanceof z.ZodError) {
    for (const zodIssue of e.issues) {
      console.error(zodIssue.code); // invalid_string
      console.error(zodIssue.message); // date format is wrong
      console.error(zodIssue.path); // ['dueDate']
    }
  }
}

 

posted @   Zhentiw  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-11-19 [Typescript] 111. Hard - String Join
2022-11-19 [Typescript] 110. Hard - Union to Tuple
2020-11-19 [React] Broadcaster + Operator + Listener pattern -- 20. useBroadcaster & useListener Example
2019-11-19 [Web] Adaptive loading
2015-11-19 [Angular + Webpack] ocLazyLoad compoment
2015-11-19 [Falcor] Retrieving Multiple Values
2014-11-19 [ES6] 05. The leg keyword -- 3. Block Scope
点击右上角即可分享
微信分享提示