9

我有一个使用 reactjs + formik + yup 的表单。我有一个多文件上传字段。我想使用 yup 验证文件格式和最大大小。我怎样才能做到这一点?

4

4 回答 4

12

扩展Devin 的答案,您可以使用 yup 实现该验证。

    const schema = Yup.object().shape({
       files: Yup.array()
         .nullable()
         .required('VALIDATION_FIELD_REQUIRED')
         .test('is-correct-file', 'VALIDATION_FIELD_FILE_BIG', checkIfFilesAreTooBig)
         .test(
           'is-big-file',
           'VALIDATION_FIELD_FILE_WRONG_TYPE',
           checkIfFilesAreCorrectType
         ),
})

验证功能在哪里:

export function checkIfFilesAreTooBig(files?: [File]): boolean {
  let valid = true
  if (files) {
    files.map(file => {
      const size = file.size / 1024 / 1024
      if (size > 10) {
        valid = false
      }
    })
  }
  return valid
}

export function checkIfFilesAreCorrectType(files?: [File]): boolean {
  let valid = true
  if (files) {
    files.map(file => {
      if (!['application/pdf', 'image/jpeg', 'image/png'].includes(file.type)) {
        valid = false
      }
    })
  }
  return valid
}
于 2019-04-08T09:56:27.927 回答
3

此代码将用于验证图像格式。

const SUPPORTED_FORMATS = ["image/jpg", "image/jpeg", "image/gif", "image/png"];

export const validateImageType = (value) => {
  if(value) {
    let type = value.match(/[^:]\w+\/[\w-+\d.]+(?=;|,)/)[0]
    return SUPPORTED_FORMATS.includes(type)
  }
}

  Yup.mixed() .test('fileSize', "File is too large", value => value.size <= FILE_SIZE) .test('fileType', "Your Error Message", value => SUPPORTED_FORMATS.includes(value.type) )

于 2020-01-20T08:49:16.440 回答
1
export const UploadFileSchema = yup.object().shape({
file: yup
    .mixed()
    .required("You need to provide a file")
    .test("fileSize", "The file is too large", (value) => {
        return value && value[0].sienter code hereze <= 2000000;
    })
    .test("type", "Only the following formats are accepted: .jpeg, .jpg, .bmp, .pdf and .doc", (value) => {
        return value && (
            value[0].type === "image/jpeg" ||
            value[0].type === "image/bmp" ||
            value[0].type === "image/png" ||
            value[0].type === 'application/pdf' ||
            value[0].type === "application/msword"
        );
    }),
});

此解决方案取自 Maksim Ivanov(在 youtube 上)

于 2021-01-26T11:58:47.830 回答
1
  const SUPPORTED_FORMATS = ['image/jpg', 'image/jpeg', 'image/png'];

  const registerSchema = Yup.object().shape({
    uriImage: Yup.mixed()
      .nullable()
      .required('A file is required')
      .test('Fichier taille',
        'upload file', (value) => !value || (value && value.size <= 1024 * 1024))
      .test('format',
        'upload file', (value) => !value || (value && SUPPORTED_FORMATS.includes(value.type))),
  });
于 2021-11-24T15:02:52.200 回答