10
votes

I have a form using reactjs + formik + yup. I have a multi file upload field. I want to validate the file format and max size using yup. How can I do this?

4

4 Answers

13
votes

Expanding on Devin's answer, you can implement that validation with 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
         ),
})

Where the validation functions are:

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
}
3
votes

This code will work for validating image formats.

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) )
1
votes
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"
        );
    }),
});

This solution is taken from Maksim Ivanov (on youtube)

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