首页 > 解决方案 > schedules[0].timings[0].startTime 必须是 `string` 类型,但最终值为:`null` - 当字段为空时获取此值

问题描述

常量验证模式 = () => {

return Yup.lazy(values => {
    return Yup.object().shape({
        name: Yup.string().required("This field is required"),
        streetAddress: Yup.string().required("This field is required"),
        city: Yup.string().required("This field is required"),
        state: Yup.string().required("This field is required"),
        zipCode: Yup.string().required("This field is required"),
        country: Yup.string().required("This field is required"),
        phone: Yup.string().required("This field is required"),
        //   consultingCharge: Yup.string().required("This field is required"),
        schedules: Yup.array().of(
            Yup.object().shape({
                available: Yup.boolean(),
                timings: Yup.array().of(
                    Yup.object().shape({
                        startTime: Yup
                            .string()
                            .when('available', {
                                is: true,
                                then: Yup.string().required('Field is required'),
                                otherwise: Yup.string()
                            }),

                        endTime: Yup
                            .string()
                            .when('available', {
                                is: true,
                                then: Yup.string().required('Field is required'),
                                otherwise: Yup.string()
                            })
                            .test("",  "End time must be after Start time" ,  function(values){
                                return this.parent.startTime < values;
                            }),

                    })
                )
            })
        )
    })
})

}

面对以下错误: schedules[0].timings[0].endTime 必须是一种string类型,但最终值为:null。如果“null”旨在作为空值,请务必将架构标记为.nullable()

何时将开始时间和结束时间字段留空。

标签: reactjsformsyup

解决方案


我不确定这是否与架构有关,我可以想象您将它与 formik 或其他表单库结合使用?看起来您正在针对该架构进行验证的状态正在null为 endTime 属性提供一个值。你能验证它不是状态对象本身的问题吗?可能是您有一个为空的输入字段并且 onChange 处理程序将值从状态设置为null而不是""?:)


推荐阅读