使用 yup 在 React 中验证字段

Validate Fields in React using yup

如何验证至少需要两个字段?

请在此处检查代码和框Click Here

const validationSearch = yup.object().shape({
  instagramProfileId: yup
    .string()
    .when(["$tiktokProfileId", "$youtubeProfileId"], {
      is: (tiktokProfileId, youtubeProfileId) =>
        tiktokProfileId && youtubeProfileId,
      then: yup.string().notRequired(),
      otherwise: yup.string().required()
    }),
  tiktokProfileId: yup
    .string()
    .when(["$instagramProfileId", "$youtubeProfileId"], {
      is: (instagramProfileId, youtubeProfileId) =>
        instagramProfileId && youtubeProfileId,
      then: yup.string().notRequired(),
      otherwise: yup.string().required()
    }),
  youtubeProfileId: yup
    .string()
    .when(["$instagramProfileId", "$tiktokProfileId"], {
      is: (instagramProfileId, tiktokProfileId) =>
        instagramProfileId && tiktokProfileId,
      then: yup.string().notRequired(),
      otherwise: yup.string().required()
    })
});

将您的 validationSearch 函数替换为:

删除所有“$”并在末尾添加一个数组,其中包含每个“when”条件中所需的字段

const validationSearch = yup.object().shape(
  {
    instagramProfileId: yup
      .string()
      .when(["tiktokProfileId", "youtubeProfileId"], {
        is: (tiktokProfileId, youtubeProfileId) =>
          tiktokProfileId && youtubeProfileId,
        then: yup.string().notRequired(),
        otherwise: yup.string().required()
      }),
    tiktokProfileId: yup
      .string()
      .when(["instagramProfileId", "youtubeProfileId"], {
        is: (instagramProfileId, youtubeProfileId) =>
          instagramProfileId && youtubeProfileId,
        then: yup.string().notRequired(),
        otherwise: yup.string().required()
      }),
    youtubeProfileId: yup
      .string()
      .when(["instagramProfileId", "tiktokProfileId"], {
        is: (instagramProfileId, tiktokProfileId) =>
          instagramProfileId && tiktokProfileId,
        then: yup.string().notRequired(),
        otherwise: yup.string().required()
      })
  },
  [
    ["tiktokProfileId", "youtubeProfileId"],
    ["instagramProfileId", "youtubeProfileId"],
    ["instagramProfileId", "tiktokProfileId"]
  ]
);

演示 : Stackblitz