【问题标题】:Validating file size and format with YUP使用 YUP 验证文件大小和格式
【发布时间】:2019-05-29 22:47:55
【问题描述】:

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

【问题讨论】:

    标签: reactjs formik yup


    【解决方案1】:

    扩展 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
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 你可以添加这个来验证大小 Yup.mixed().test('fileSize', "File Size is too large", value => value.size
      • 你在哪里使用这个函数“validateImageType”?
      • 应该是测试函数的第三个参数
      【解决方案3】:
      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 上)

      【讨论】:

      • 我不确定 Formik 但这不适用于 React Hook Form。 RHF 的问题是文件字段永远不会为空。如果没有文件,它将包含一个空的FileList。要检查required 要求,您需要白化您自己的验证器功能。这是实现了这种验证的文件的link
      【解决方案4】:
        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))),
        });
      

      【讨论】:

        猜你喜欢
        • 2019-10-05
        • 2021-11-05
        • 1970-01-01
        • 2019-12-26
        • 2022-11-19
        • 2019-09-29
        • 1970-01-01
        • 2013-12-17
        • 1970-01-01
        相关资源
        最近更新 更多