formik: TypeError: Cannot read property 'length' of undefined when using Yup.addMethod()
I’m using formik with yup and using Yup.addMethod().
I’m using React 16.5
Example:
validationSchema: Yup.object().shape({ file:Yup.addMethod(Yup.string, 'file',(file)=>{ console.log(file); return "This is not a valid file."; }) }),
I’m getting error:
TypeError: Cannot read property ‘length’ of undefined
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Reactions: 2
- Comments: 17 (1 by maintainers)
For those coming after me, what I realized is that the yup test method actually doesn’t accept an arrow function.
Doesn’t work:
Works:
What @fullmetalsheep wrote helped me in one case. Other case was that my custom
string().test()method had an error inside and crashed silently resulting in this message. See inside all your customtest()methods if they do not crash (In my case I didn’t handleundefinedvalue passed to it)@tannerhallman actually, it’s not that it doesnt accept arrow functions. It’s because you’re referencing
thisinside of your arrow function.thisdoes NOT have the proper Yup context so it errors out.reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Invoked_through_call_or_apply
So this happens when you has an error in your custom validation function
In my case the error was
So yup will throw here https://github.com/jaredpalmer/formik/blob/c5243947fcf21cd873dd86b57689a30ffc46eab8/src/Formik.tsx#L258
if there is real validation errors or if there is an error in the validation function
so this will throw https://github.com/jaredpalmer/formik/blob/c5243947fcf21cd873dd86b57689a30ffc46eab8/src/Formik.tsx#L683
We can check if yupError has
inner, and if not, we should show the error to end userwhat do you guys think of this solution?
@raq929 , @nathanhannig
Make sure the specific property of
initialValuesyou’re checking inside thevalidationSchemais also present inside thevalidationSchema.See this answer for an example: https://stackoverflow.com/questions/49394391/conditional-validation-in-yup?rq=1
@deadcoder0904 the error could be coming from the regex that you used to validate password, instead of using quote around the regex (‘{regex}’) trying using forward slash (/{regex}/) before:
Password: yup.string().matches('^(?=.*[a-z])(?=.*[A-Z])(?=.*d)[a-zA-Zd]$').required(),after:
Password: yup.string().matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*d)[a-zA-Zd]$/).required(),see the doc for reference: https://github.com/jquense/yup#stringmatchesregex-regex-message-string--function-schema
@deadcoder0904 maybe try replacing ‘Confirm Password’ with something like confirmPass? I’m currently travelling and have no method of testing code sorry 😦