How To Validate File Size With Yup
TypeScript
17/11/2022
Yup does not provide any out of the box validation for files. Fortunately, one can use tests a.k.a assertions to provide custom validation. Let's take a look 👀 at the function definition of such an assertion.
Schema.test(name: string, message: string | function | any, test: function): SchemaIn the 1st parameter, we pass in a name for the test, e.g. fileSize. The 2nd parameter takes in a message that would be displayed in case of a failed ❌ assertion. Lastly, the final parameter is a function that evaluates the passed in value (in this case a file) and returns a boolean.
Here's a code example of how one would implement the custom file validation.
const schema: yup.SchemaOf<ExampleFormInput> = yup.object({ // ... other fields fileUpload: yup .mixed<FileList>() // Pass in the type of `fileUpload` .test( "fileSize", "Only documents up to 2MB are permitted.", files => !files || // Check if `files` is defined files.length === 0 || // Check if `files` is not an empty list Array.from(files).every(file => file.size <= 2_000_000) ),})We define the fileUpload field of type mixed and pass in a generic FileList type. If you were to inspect/log the file data you obtain from your input tag, it would look as follows: [ File, File ].
Concerning the validation logic, we first check if files is defined. If it is, then we check if any files exists in the list. Lastly, we convert the file list into an array so we can run the every method on it to check if all the uploaded files are below 2MB.