How to validate file size with yup and formik

Asked
Active3 hr before
Viewed126 times

8 Answers

90%

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?,Just handle it on your own -- yup isn't great at validating files I've found.,This code will work for validating image formats.

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
}
load more v
88%

I couldn't find any doc for file upload validation in formik and yup. Please help me how to do that ?, .test( "fileSize", "File too large", (value) => value && value.size <= FILE_SIZE ),Yup doesn’t handle this. You can use your own validation function at either the form or field-level.

        yup.object().shape({
                 file: yup.mixed().required('A file is required')
                    .test('fileFormat', 'PDF only', (value) => {
                       console.log(value);
                       return value && ['application/pdf'].includes(value.type);
                    }),
load more v
72%

After following this tutorial to integrate a file upload component in my form https://hackernoon.com/formik-handling-files-and-recaptcha-209cbeae10bc I've been able to test file size and type like this: iconFile: Yup.mixed() .test('fileSize', "File Size is too large", value => value.size <= FILE_SIZE) .test('fileType', "Unsupported File Format", value => SUPPORTED_FORMATS.includes(value.type) ), Ask questionsHow to validate formik & Yup validation with file type and size ? ,I couldn't find any doc for file upload validation in formik and yup. Please help me how to do that ?

PS: I have fixed this by added validation for value like @zephsibley's code:

value && typeof value.arrayBuffer === 'function'
65%

I couldn’t find any doc for file upload validation in formik and yup. Please help me how to do that ?,@jaredpalmer Is there any way we can validate using validate and validateScheme in a single form?,In this sandbox, I’ve just updated the version of Formik to 2.0.3, and I’ve got undefined instead of the file size: https://codesandbox.io/s/yup-formik203-14vlq

Pretag
 Pretag team - issue, fix, solve, resolve
75%

Pretag
 Pretag team - issue, fix, solve, resolve
40%

And this is the relevant part of the validationSchema:, Java Questions , Java Questions

<Formik 
  initialValues={{
   ...initialValues, //no need to list them all here
   affiliateLogo: null,
  }} 
  validationSchema={validationSchema}
  onSubmit(values=>{//do something with the values})
>
 {(
   values,
   errors,
   touched, 
   setFieldValue,
   handleSubmit,
   handleChange,
   handleBlur
) => <form>...</form>}
</Formik>
load more v
22%

Form validation without the use of a library,The formValues variable holds the data the user puts into the input fields.,errors This object holds the validation errors that correspond to each input field, and is populated with the definitions we passed into the Yup object schema.

const SignInForm = () => {
  return (
    <Formik
      initialValues={initialValues}
      validate={validate}
      onSubmit={submitForm}
    >
      {(formik) => {
        const {
          values,
          handleChange,
          handleSubmit,
          errors,
          touched,
          handleBlur,
          isValid,
          dirty
        } = formik;
        return (
            <div className="container">
              <h1>Sign in to continue</h1>
              <form onSubmit={handleSubmit}>
                <div className="form-row">
                  <label htmlFor="email">Email</label>
                  <input
                    type="email"
                    name="email"
                    id="email"
                    value={values.email}
                    onChange={handleChange}
                    onBlur={handleBlur}
                    className={errors.email && touched.email ? 
                    "input-error" : null}
                  />
                  {errors.email && touched.email && (
                    <span className="error">{errors.email}</span>
                  )}
                </div>

                <div className="form-row">
                  <label htmlFor="password">Password</label>
                  <input
                    type="password"
                    name="password"
                    id="password"
                    value={values.password}
                    onChange={handleChange}
                    onBlur={handleBlur}
                    className={errors.password && touched.password ? 
                     "input-error" : null}
                  />
                  {errors.password && touched.password && (
                    <span className="error">{errors.password}</span>
                  )}
                </div>

                <button
                  type="submit"
                  className={dirty && isValid ? "" : "disabled-btn"}
                  disabled={!(dirty && isValid)}>
                  Sign In
                </button>
              </form>
            </div>
        );
      }}
    </Formik>
  );
};
load more v
60%

In order to validate our forms, we will use both react-dropzone and Yup with Formik validationSchema.,In this tutorial, we’ll build a multiple file upload with drag-n-drop and a progress bar using Next.js, React, react-dropzone, Formik and Yup for validation.,In order to add a nice look and feel to our multi upload form, we will use Material-UI Progress component.

In the NavMenu.razor component delete the next lines of code

<li class="nav-item px-3">
   <NavLink class="nav-link" href="counter">
      Counter
   </NavLink>
</li>
<li class="nav-item px-3">
   <NavLink class="nav-link" href="fetchdata">
      Fetch data
   </NavLink>
</li>

Other "undefined-undefined" queries related to "How to validate file size with yup and formik"