我无法弄清楚如何使用 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/