This might look long, but it’s only because I want to make sure to provide all the info that I have. So I have a Formik form in a react component which handles a couple of text inputs and a few file uploads. I am using this Formik component within a React class component:
<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>
This is the file upload input field:
<input type="file" id="affiliateLogo" name="affiliateLogo" onChange={event => setFieldValue('affiliateLogo', event.currentTarget.files[0])} onBlur={handleBlur} /> //validation error message added to every input field as below { errors.affiliateLogo && touched.affiliateLogo ? <p className="errors">{errors.affiliateLogo}</p> : null }
And this is the relevant part of the validationSchema:
affiliateLogo: Yup.mixed() .test('fileType', 'Unsupported File Format', function (value) { const SUPPORTED_FORMATS = ['image/jpg', 'image/jpeg', 'image/png']; return SUPPORTED_FORMATS.includes(value.type) }) .test('fileSize', "File Size is too large", value => { const sizeInBytes = 500000;//0.5MB return value.size <= sizeInBytes; })
For some reason, when Yup.mixed().test() is added to the validationSchema, the form validation breaks: validation errors are not shown until I select a file with the file input and only then do suddenly error messages appear (the problem is not the validation itself, but displaying the validation results in form of error messages).
So let’s say I try to submit an untouched form -I expect all the error messages to appear (because form validaition should be triggered by Formik on submit) but instead nothing happens when this file input is hooked up with a Yup.mixed().test() validator. Then I go on and select a file which makes all the error messages appear(including the right error message for the file input itself).
Or another example: I visit a text field which is required and then leave it without typing anything into it. If I comment out the Yup.mixed().test() validator, this works just fine (error message appear on blur). When the validator is there, nothing happens-the validation error message does not appear, only when I select a file with the file input field.
I have been looking at both the Yup and Formik documentation and couldn’t find anything about this, neither here on stack overflow.
Can somebody please point out what am I missing?
Thank you in advance.
Advertisement
Answer
Chances are your validator is throwing an unexpected error. console.log(value)
– you’ll probably find out that it’s not an obect at some point and trying to access size and type properties throw an error that causes validation to break.