使用 Yup 验证非必填数字字段

Laz*_*nds 9 javascript reactjs yup

我正在尝试验证一个可选的数字字段,因此允许为空。如果该字段中有值,则该值必须是正数。

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'],
    ]
);
Run Code Online (Sandbox Code Playgroud)

它允许表单的其余部分在字段为空时以及其中有正数时进行验证,但如果我输入负数或字符串,它不会返回任何应有的错误。

Gee*_*Gee 9

对于下一个在这里尝试做同样事情的人来说,这适用于可以是 0、null、未定义或空字符串的正数,但不适用于任何其他字符串或负数:

const schema = yup.object().shape({
    gpa: yup.number()
         .typeError("GPA must be a number")
         .nullable()
         .moreThan(0, "Floor area cannot be negative")
         .transform((_, val) => (val !== "" ? Number(val) : null)),
    }
);
Run Code Online (Sandbox Code Playgroud)

Number 转换会触发字符串上的类型错误,这将给您在 .typeError() 中定义的错误,并且使用 .moreThan() 而不是 .positive() 允许您有零(如果不这样做,请切换到 .positive() )不想允许 0)。