Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating file presence with YUP

I'm using Yup to validate my form. In one of my form, I want to validate that one <input type="file" /> has a file.

I've tested this (and it's not working):

Yup.object().shape({
  file: Yup.object().shape({
    name: Yup.string().required()
}).required('File required')

I've the following error message in the console:

file must be a object type, but the final value was: null (cast from the value {}). If "null" is intended as an empty value be sure to mark the schema as .nullable()

Any idea?

like image 242
cappie013 Avatar asked Sep 20 '18 14:09

cappie013


People also ask

What is Yup validation?

Yup is a JavaScript schema builder for value parsing and validation. Define a schema, transform a value to match, validate the shape of an existing value, or both. Yup schema are extremely expressive and allow modeling complex, interdependent validations, or value transformations.

How do you validate field only exists?

You can set a additional boolean key where value is default false. Change it to true when you modify the value in step 1. And then if the value is true for that key then apply the validation.


1 Answers

Here is how I did it

import { object, string, mixed } from "yup"

const schema = object().shape({
  attachment: mixed().test("fileSize", "The file is too large", (value) => {
    if (!value.length) return true // attachment is optional
    return value[0].size <= 2000000
  }),
})
like image 146
2JN Avatar answered Oct 06 '22 01:10

2JN