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?
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.
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
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.
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
}
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))),
});
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