【问题标题】:Validate Fields in React using yup使用 yup 验证 React 中的字段
【发布时间】:2021-11-01 21:22:21
【问题描述】:

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

请在此处检查代码框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()
    })
});

【问题讨论】:

    标签: reactjs ecmascript-6 react-hooks yup


    【解决方案1】:

    将你的validationSearch函数替换为:

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

    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

    【讨论】:

      猜你喜欢
      • 2019-09-29
      • 2019-01-06
      • 2021-12-05
      • 2019-07-11
      • 2021-12-04
      • 2020-07-21
      • 2019-07-23
      • 1970-01-01
      • 2019-07-09
      相关资源
      最近更新 更多