11

我有

StartIntensity: yup.number(),
EndIntensity: yup
    .number()
    .when(
        "StartIntensity",
        (StartIntensity: number, schema: any) => {
            return !!StartIntensity
                ? schema.moreThan(
                        StartIntensity,
                        "Max should be > min"
                  )
                : schema;
        }
    ),

但我需要这样的东西

StartIntensity: yup.number(),
EndIntensity: yup
    .number()
    .when(
        "StartIntensity, EndIntensity",
        (StartIntensity: number, EndIntensity: number, schema: any) => {
            return !!StartIntensity && StartIntensity !== EndIntensity
                ? schema.moreThan(
                        StartIntensity,
                        "Max should be > min"
                  )
                : schema;
        }
    ),

但上面的代码不能正常工作。是否有可能以其他方式执行此验证?

4

1 回答 1

31

在您的情况下,.when()的第一个参数应该是一个键数组:

StartIntensity: yup.number(),
EndIntensity: yup
    .number()
    .when(
        ["StartIntensity", "EndIntensity"],
        (StartIntensity: number, EndIntensity: number, schema: any) => {
            return !!StartIntensity && StartIntensity !== EndIntensity
                ? schema.moreThan(
                        StartIntensity,
                        "Max should be > min"
                  )
                : schema;
        }
    ),

键:字符串 | 大批

https://github.com/jquense/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-schema

如果上面的代码抛出“循环依赖”错误(我认为它会),试试下面的代码:

StartIntensity: yup.number(),
EndIntensity: yup
    .number()
    .when('StartIntensity', (StartIntensity, schema) => {
      return schema.test({
        test: EndIntensity => !!StartIntensity && EndIntensity > StartIntensity,
        message: "Max should be > min"
      })
    }),

或者您也可以使用ref

StartIntensity: yup.number(),
EndIntensity: yup
    .number()
    .moreThan(yup.ref('StartIntensity'), "Max should be > min")
于 2019-05-21T22:32:04.563 回答