【发布时间】:2021-12-05 23:22:43
【问题描述】:
我正在尝试验证一个可选的数字字段,因此允许为空。如果字段中有值,则必须为正数。
const schema = yup.object().shape({
gpa: yup.number()
.when('gpa', {
is: (value) => value?.length > 0,
then: yup.number().positive(numberPositiveMessage).typeError(numberMessage),
otherwise: yup.number().notRequired().nullable(true).transform(value => (isNaN(value) ? undefined : value))
},
[
['gpa', 'gpa'],
]
);
它允许表单的其余部分验证字段何时为空,以及其中是否有正数,但如果我输入负数或字符串,它不会返回任何应有的错误。
【问题讨论】:
标签: javascript reactjs yup