Yup循环依赖项:两个相互依赖的字段

时间:2020-08-10 15:12:20

标签: javascript node.js yup

我有以下Yup验证模式

 const validationSchema = Yup.object().shape({
  name: Yup.string(),
  services: Yup.array(Yup.string().oneOf(SERVICES, "Invalid service!")),
  locations: Yup.array(Yup.string().oneOf(LOCATIONS, "Invalid location!")),
  distance: Yup.number()
    .typeError("Invalid distance!")
    .positive("Invalid distance!")
    .when("userFormattedAddress", {
      is: (val) => !!val,
      then: Yup.number().required(),
      otherwise: Yup.number(),
    }),
  userFormattedAddress: Yup.string("Invalid user location!").when("distance", {
    is: (val) => !!val,
    then: Yup.string().required(),
    otherwise: Yup.string(),
  }),
  userCoordinates: Yup.array(
    Yup.number("Invalid user location!").positive("Invalid user location!")
  ),
});

期望的行为是,当输入距离时,用户必须输入地址,而当用户输入地址时,他们也必须指定距离。但是,我遇到了周期性依赖关系...有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

好的,我找到了答案:

 const validationSchema = Yup.object().shape({
 name: Yup.string(),
 services: Yup.array(Yup.string().oneOf(SERVICES, "Invalid service!")),
 locations: Yup.array(Yup.string().oneOf(LOCATIONS, "Invalid location!")),
 distance: Yup.number()
   .typeError("Invalid distance!")
   .positive("Invalid distance!")
   .when("userFormattedAddress", {
     is: (val) => !!val,
     then: Yup.number().required(),
     otherwise: Yup.number(),
   }),
 userFormattedAddress: Yup.string("Invalid user location!").when("distance", {
   is: (val) => !!val,
   then: Yup.string().required(),
   otherwise: Yup.string(),
 }),
 userCoordinates: Yup.array(
   Yup.number("Invalid user location!").positive("Invalid user location!")
 ),
}, ["distance", "userFormattedAddress"]);

您需要在其中将数组中的字段作为noSortedEdges参数传递

相关问题