【问题标题】:Yup validation based on value of another field是的,基于另一个字段的值的验证
【发布时间】:2021-06-29 05:12:05
【问题描述】:

我有三个字段:Formik 形式的referenceMonth(string)、openingDate(string)、closureDate(string)。 当openingDatreferenceMonth 不是同一个月时,我会向openingDate 添加一个错误。

export const VALIDATION_SCHEMA = Yup.object().shape({
    'referenceMonth' : Yup.number().required(YUP_DEFAULT_ERROR_VALUE),
    'openingDate' : Yup.string().when(['referenceMonth', 'openingDate'], {
        is: (referenceMonth: string, openingDate: string) => 
             referenceMonth !== `${new Date(openingDate).getMonth()}`,
        then: Yup.string().required('Select right month')
    }),
})

终端说:错误:循环依赖,节点是:“openingDate”。

【问题讨论】:

    标签: javascript reactjs yup


    【解决方案1】:

    需要对相互依赖、需要验证的字段进行排序,以便按所需顺序构建它们。您可以通过按特定顺序在末尾添加需要验证的字段来尝试这种方式吗:

    export const VALIDATION_SCHEMA = Yup.object().shape({
        'referenceMonth' : Yup.number().required(YUP_DEFAULT_ERROR_VALUE),
        'openingDate' : Yup.string().when(['referenceMonth', 'openingDate'], {
            is: (referenceMonth, openingDate) => 
                 referenceMonth !== `${new Date(openingDate).getMonth()}`,
            then: Yup.string().required('Select right month')
        }),
    }, [['referenceMonth', 'openingDate']])
    
    

    【讨论】:

      【解决方案2】:

      由于您对openingDate 的验证非常简单,因为openingDate 的架构不会改变(根据我的理解),我建议您使用test 而不是when。你可以像这样用test替换你的when

      .test("dateTest", "Select right month", function (value) {
         return this.parent.referenceMonth !== `${new Date(value).getMonth()}`;
       })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-06
        • 1970-01-01
        • 1970-01-01
        • 2020-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多