如何将 zod 与 validator.js 一起使用

发布于 2025-01-13 18:50:40 字数 197 浏览 5 评论 0原文

我有一个使用 zod 的应用程序,但我想使用不同库 (validator.js) 中的一些方法 zod 文档说:

查看 validator.js 以获取一堆其他有用的字符串验证函数。

不确定这是否意味着这个功能是在 zod 上实现的,或者我还必须安装 validator.js,在其他情况下我如何一起使用这两个库?找不到任何例子。

谢谢!

I have an application using zod but I'd like to use some methods from a different library (validator.js) zod documentation says:

Check out validator.js for a bunch of other useful string validation functions.

Not sure if that means this functions are implemented on zod, or I have to also install validator.js, in that other case how I can use both libraries together? cant find any example.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

香草可樂 2025-01-20 18:50:40

我认为 Zod 意味着您可以安装 validator.js 并通过 Zod 使用它们的验证。 Zod 的 refine 函数使这变得相当简单。例如,如果您想使用 Zod 和验证器将字符串验证为信用卡号,它可能看起来像这样

import { z } from "zod";
import isCreditCard  from "validator/lib/isCreditCard";

const userSchema = z.object({
  name: z.string(),
  creditCard: z.string().refine(isCreditCard, {
    message: 'Must be a valid credit card number'
  }),
})

console.log(userSchema.safeParse({
  name: 'Doug',
  creditCard: '1234',
}));

console.log(userSchema.safeParse({
  name: 'steve',
  creditCard: '4000 0200 0000 0000'
}));

第一个示例失败,并显示包含我们自定义错误消息的 ZodError。第二个例子成功了。

I think Zod means that you could install validator.js and use their validations with Zod. Zod's refine function makes this fairly straightforward. For example if you wanted to validate a string as a credit card number using Zod and validator it might look something like this

import { z } from "zod";
import isCreditCard  from "validator/lib/isCreditCard";

const userSchema = z.object({
  name: z.string(),
  creditCard: z.string().refine(isCreditCard, {
    message: 'Must be a valid credit card number'
  }),
})

console.log(userSchema.safeParse({
  name: 'Doug',
  creditCard: '1234',
}));

console.log(userSchema.safeParse({
  name: 'steve',
  creditCard: '4000 0200 0000 0000'
}));

The first example fails with a ZodError containing our custom error message. The second example succeeds.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文