javascript - Zod - 检查数字类型的位数

标签 javascript typescript zod

我无法弄清楚如何使用 Zod 检查数字的位数。

由于我将字符串值转换为数字,因此无法使用 min() 或 max() 来检查位数。

在构建架构时,我尝试使用 lte() 和 gte() 进行以下操作:

export const MySchema = z.object({
  type1: z.coerce.string(),
  type2: z.coerce.string(),
  type4: z.coerce.number().lte(5).gte(5),
  type5: z.coerce.number()
})

我的目标是将 type4 限制为 5 位数字的固定长度以进行验证。什么是替代解决方案?也许在转换为数字之前检查字符串长度?

最佳答案

如果数字必须是整数,则无需特殊转换或预处理即可实现:

// Omitting the wrapper stuff
z.coerce.number() // Force it to be a number
  .int() // Make sure it's an integer
  .gte(10000) // Greater than or equal to the smallest 5 digit int
  .lte(99999) // Less than or equal to the largest 5 digit int

如果数字可以是小数,那么这个问题的另一个答案可能是您最好的选择。

关于javascript - Zod - 检查数字类型的位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75531294/

相关文章:

javascript - Angular2 rc5> 组件未加载

typescript - 强制类型是接口(interface)的子类型并扩展编号

typescript - 如果可用则让 Zod 解析,如果不可用则跳过元素

javascript - 从输入文本框中获取值

node.js - 如何在 Node 中使用 Azure 托管服务标识访问 Key Vault?

javascript - 如何使用 .map 和 for 循环编写列和行

next.js - Zod 基于 Next.js 中事件区域设置的动态错误消息

typescript - 基于 Zod 模式将接口(interface)通用化

javascript - slideToggle() 导致第一个 li a 在点击时跳转

javascript - HTML:谁负责显示/隐藏滚动条?