是的,如果值键入以 0 开头,则不会触发错误



基本上,我有一个字段需要验证如下:

export const validationSchemaWithdraw = Yup.object().shape({
amount: Yup.number()
.min(1, 'The minimum amount is one')
.typeError('The amount invalid')
.required('The amount is required'),
});

如果我输入的数量等于0,应该触发错误。但是如果value为01,什么也没发生

如果值键入以0开始,我的字段如何触发错误?

由于在yup模式上将值类型声明为number,因此在验证之前将输入值强制转换为number。像"01"这样的值将被解析为1,根据您的验证链,它是有效的。

实现您期望的行为的一种方法是在验证链中添加自定义test函数并测试前导零情况。这需要访问字段的原始值作为字符串(在通过yup转换为number之前),否则解析将忽略前导零。因此,请确保输入字段的类型为"string"

const SignupSchema = Yup.object().shape({
amount: Yup.number()
.min(1, 'The minimum amount is one')
.typeError('The amount invalid')
.required('The amount is required')
.test(
'no-leading-zero',
'Leading zero is not allowed',
(value, context) => {
return context.originalValue && !context.originalValue.startsWith('0');
}
),
});

另一种选择是将模式上的值类型更改为string,并使用matches+ regex检查字符串格式。

amount: yup
.number()
.typeError('The amount invalid')
.min(1, "The minimum amount is one")
.required('The amount is required')
.test( 'no-leading-zero', 'Leading zero is not allowed', 
(value, context) => { 
return (value && value>=1) && (context.originalValue && 
context.originalValue.startsWith("0") ) ? false:true ; 
} 
),

最新更新