yup-phone: notRequired() with empty string causes validation to fail
There is no way to make a field optional but validate when not an empty string.
Yup.string().phone(true, false, 'Phone not valid').notRequired()
About this issue
- Original URL
- State: open
- Created 4 years ago
- Reactions: 23
- Comments: 15 (5 by maintainers)
To add here from @kmacoder
Or actually a better workaround without creating additional values like ‘isPhoneBlank’ is to add new method to yup where we can conditionally validate different schemas if value is blank:
Or simply use .test method in schema without adding new method:
@dan003400 I think this works as a workaround:
Using .when() referencing a sibling boolean key/value pair let’s you check if the phone string is blank, and only use yup-phone if it isn’t.
On the off chance you’re using Formik doing this quick check whenever validations happen seems to be working alright:
This was how I fixed empty field validation.
According to yup string.ensure() documentation
I hope this works for someone. All thanks to @abhisekp. Happy coding.
Hi folks, I really need this change for a project, Can I be of any help to make this PR merged asap ? (already looked at @nightness changes and it seems fine to me !)
Thanks for your PR @nightness
@abhisekp Just did the PR.
@nightness Would you like to file a PR with the given code?