问题描述
我制定了这样的模式:
const schema = yup.object().shape({
seats: yup
.number()
.label('seats')
.required('pls enter'),});
另外,我想检查该数字是否为正数或大于0。是否可以将这种条件添加到模式中?
解决方法
您可以使用test()
方法并在其中添加自定义验证:
number: Yup.number()
.required('ERROR: The number is required!')
.test(
'Is positive?','ERROR: The number must be greater than 0!',(value) => value > 0
)
https://github.com/jquense/yup#mixedtestname-string-message-string--function-test-function-schema
,实际上,Yup提供了以下功能:https://github.com/jquense/yup#numberpositivemessage-string--function-schema
,您可以使用 .positive()
也可以使用 .min(1)
const schema = yup.object().shape({
seats: yup
.number()
.positive()
.label('seats')
.required('pls enter')
.min(1),});