Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating file size and format with YUP

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?

like image 665
ComCool Avatar asked Jan 03 '19 10:01

ComCool


People also ask

What is Yup?

What is Yup? Yup is a JavaScript object schema validator. Lets understand the above definition with an example. Consider everday common feature of login form with fields "username" and "password". Before submitting form we want to verify that user has entered all fields.

How many times Yup validation with multiple values fails?

yup validation on multiple values 7 Validating a react-final-form form with yup and custom validations 0 Yup: Validation with test failes 12 Yup nested schema validation

How to use yup with formik?

It very simple to use Yup with formik. We just need to pass the validator object to formik 's validationSchema option. All the Yup 's validation errors are transformed into formik state variables. Which can be used to show error messages.


2 Answers

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
}
like image 135
pfulop Avatar answered Oct 07 '22 07:10

pfulop


  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))),
  });
like image 21
jacobit kashala Avatar answered Oct 07 '22 06:10

jacobit kashala