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?
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.
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.
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
}),
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With