如何使用 Yup 验证一个字段与另一个字段?

col*_*lin 8 reactjs yup

我正在设置一个包含两个字段的表单;开始月份和结束月份。

开始月份和结束月份仅用相应月份的整数(0-11)表示。我需要验证以确保结束月份在开始月份之后(即结束月份的整数更大)。

几年前我看过其他类似的问题,但是是的,似乎已经更新以使它们无用。我已经尝试了下面的代码,但有一些变化。

我也很难将结束月份验证为一个数字(.number()- 我假设我可能必须在测试函数中执行此操作。

let schema = yup.object().shape({
  startMonth: yup
    .number()
    .required()
    .positive()
    .integer(),
  endMonth: Yup.string().test(
  "End Month Validation",
  "error message",
  value => {
    return value > startMonth;
  }
)
.number()
.required()
.positive()
.integer(),
});
Run Code Online (Sandbox Code Playgroud)

错误:第 102 行:'startMonth' 未定义 no-undef

Dac*_*nny 17

另一种方法是利用.ref().moreThan()执行此验证逻辑。

类似以下的内容应该可以达到您的要求:

let schema = Yup.object().shape({
  startMonth: Yup
    .number()
    .required()
    .positive()
    .integer(),
  endMonth: Yup.number() /* Remove .string() */
    .required()
    .positive()
    /* Reference startMonth field in validating endMonth value */
    .moreThan(Yup.ref('startMonth'), "End month must come after start month")
    .integer(),
});

schema.validate({ startMonth : 1, endMonth : 2 })  // Okay!
schema.validate({ startMonth : 11, endMonth : 2 }) // Throws exception
Run Code Online (Sandbox Code Playgroud)

希望有帮助!