formik: Why are empty strings mapped to undefined before validation?
I’m wondering what the reason for this code is
I want to have an input which is either null (i.e. hidden) or a string but cannot be an empty string.
yup
.string()
.notOneOf([''], 'Required')
.nullable()
This doesn’t work if the field in question is at the top level of the form due to the coercing of '' to undefined which makes yup ignore the field if its value is empty. But what’s even more unexpected is that it does work when the field is nested in a sub object since the coercion is not recursive.
I’m sure there’s a good reason for this behaviour and I would like to understand it.
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Comments: 19 (4 by maintainers)
I had the same problem with
Yup.string().defined()and Formik.My current workaround is to use
Yup.string().default('').defined(): Formik changes''toundefinedbefore passing in the value to Yup, Yup then changesundefinedback to''before validation.Very ugly of course…
I am also facing the same problem! Does anyone have a solution?
Ironically, I found out about this behavior because I tried refactoring a form to use react-hook-form instead of Formik, and all of my (non-required) number fields triggered unwanted type errors when validation ran with those fields left blank. Turns out Formik was handling those empty string values all along! I now wish that yup had a global option to enable that behavior. Looks like I need to go add a bunch of transforms for those optional number fields. (If anyone has run into this and found a great solution, I’d love to hear it!)
Ian (eonwhite) is on his honeymoon right now and I don’t want to ping him. He wrote that part initially IIRC. He’ll be back in a week or so.