Yup两位小数数字校验Schema问题:输入0提示错误求解决
问题排查与修复
问题根源
输入0触发校验错误的核心原因,是test函数里的(val || "")逻辑:数字0属于JavaScript假值,会被转换成空字符串"",而你的正则/^\d+(\.\d{0,2})?$/不匹配空字符串,因此返回false触发错误。
修复后的Schema
直接去掉多余的|| ""判断即可——前面已经通过val == null过滤了空值情况,非空的val必然是数字类型,可以直接调用toString():
export const NumberWithTwoDecimalPlaces = Yup.number() .typeError("Must be numeric") .nullable() .transform((value: number, originalValue: string) => // allow empty strings (avoids casting to NaN) originalValue === "" ? null : value ) .test( "decimal-places", "Incorrect value", (val: number | null | undefined) => val == null || /^\d+(\.\d{0,2})?$/.test(val.toString()) );
可选优化
如果需要禁止整数部分的前导零(比如不允许012.34这类格式),可以把正则调整为/^(0|[1-9]\d*)(\.\d{0,2})?$/,这样既保留单独的0为合法值,也能限制非零整数不能有前导零。
内容的提问来源于stack exchange,提问作者Michal Sakowski
相关产品推荐
相关产品推荐

