是的:将字段本身与另一个字段进行比较

时间:2019-05-21 15:43:12

标签: javascript yup

我有

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;
        }
    ),

,但是上面的代码无法正常工作。是否有可能通过其他方式执行此验证工作?

1 个答案:

答案 0 :(得分:1)

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

---
apiVersion: v1
kind: Service
metadata:
  name: ambassador
spec:
  type: LoadBalancer
  externalTrafficPolicy: Local
  ports:
   - port: {custom port}
     targetPort: 8080
  selector:
    service: ambassador
  

键:字符串|数组

https://github.com/jquense/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-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;
        }
    ),

或者您也可以使用 ref

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