如何使用yup验证reactjs中上传的文件数量

问题描述 投票:0回答:1

我有一个reactjs表单,要求用户上传至少3个文件。如何编写验证模式?

reactjs formik yup
1个回答
0
投票

您可以为 yup 定义一个模式并使用 yup.array().of(...).min(...),如下所示:

import * as Yup from "yup";

const validFileExtensions = {
  image: ["jpg", "gif", "png", "jpeg", "svg", "webp"],
};

function isValidFileType(fileName, fileType) {
  return (
    fileName &&
    validFileExtensions[fileType].indexOf(fileName.split(".").pop()) > -1
  );
}

function getAllowedExt(type) {
  return validFileExtensions[type].map((e) => `.${e}`).toString();
}

const Schema = Yup.object().shape({
  images: Yup.array()
    .of(
      Yup.mixed()
        .required("Required")
        .test("is-valid-type", "Not a valid image type", (value) =>
          isValidFileType(value && value.name.toLowerCase(), "image")
        )
        .test(
          "is-valid-size",
          "Max allowed size is 100KB",
          (value) => value && value.size <= MAX_FILE_SIZE
        )
    )
    .min(3),
});
© www.soinside.com 2019 - 2024. All rights reserved.