reactjs 使用YUP验证文件大小和格式

2exbekwf  于 2023-06-29  发布在  React
关注(0)|答案(6)|浏览(130)

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

gab6jxml

gab6jxml1#

Devin's answer的基础上进行扩展,您可以使用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
}
xxb16uws

xxb16uws2#

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上)

3qpi33ja

3qpi33ja3#

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))),
  });
fcg9iug3

fcg9iug34#

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

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) )
zpgglvta

zpgglvta5#

图片:

Yup.mixed().test(1000, "File Size is too large", value => value.size <= FILE_SIZE) .test('fileType', "Unsupported File Format", value => SUPPORTED_FORMATS.includes(['image/*']) )

https://hackernoon.com/formik-handling-files-and-recaptcha-209cbeae10bc

rsl1atfo

rsl1atfo6#

基于pfulop's answer,以下是我必须做的,让它工作:

const maxFileSize = 800 * 1024 // 800 kilobytes
const fileTypes = ['image/png', 'image/jpg', 'image/jpeg']

const schema = yup.object().shape({
  first_name: yup.string().required(),
  last_name: yup.string().required(),
  email: yup.string().email().required(),
  avatar: yup.mixed().test('fileSize', appTranslation.ERROR_FILE_SIZE, (value) => {
    if (!value) return true
    return isFileSizeValid([value], maxFileSize)
  }).test('fileType', appTranslation.ERROR_FILE_TYPE, (value) => {
    if (!value) return true
    return isFileTypesValid([value], fileTypes)
  })
})

export function isFileSizeValid(files: [File], maxSize: number): boolean {
    let valid = true
    if (files) {
        files.map(file => {
            const fileSize = file.size
            if (fileSize > maxSize) {
                valid = false
            }
        })
    }
    return valid
}

export function isFileTypesValid(files: [File], authorizedExtensions: string[]): boolean {
    let valid = true
    if (files) {
        files.map(file => {
            if (!authorizedExtensions.includes(file.type)) {
                valid = false
            }
        })
    }
    return valid
}

我在代码中重用函数,这就是为什么我添加了maxSize & authorizedExtensions或export关键字。最重要的变化是const schema。

相关问题