Yup conditional validation with Formik
See original GitHub issueI’m trying to make a field “old_password” required only if another filed “password” is filled with some value.
It works when using the .when()
function in Yup, but when the other field “password” gets empty, the “old_password” still gives me the error message that it is required, even though the “password” is empty.
Also when I implement this, the “name” field validation is not working anymore for some reason. And it works when I type in the “password” field 😕
I don’t know how to solve this.
Here’s a sample code …
Issue Analytics
- State:
- Created 4 years ago
- Comments:6 (3 by maintainers)
Top Results From Across the Web
Conditional validation with Yup and Formik - Stack Overflow
Conditional validations with YUP : ; 1. Single value, simple condition : RULE: Only ask for personName when isPerson true. ; 2. Single...
Read more >Yup conditional validation with Formik - CodeSandbox
CodeSandbox is an online editor tailored for web applications.
Read more >How To Do Conditional Validation With Formik and Yup
Formik and Yup provides a nice easy way to do conditional validation for your React projects. Using the when method you can conditionally...
Read more >Conditional validation of form fields using Yup
How to enable or disable validation on Formik form fields based on certain conditions in Yup.
Read more >Validation - Formik
Because we ❤️ Yup sooo much, Formik has a special config option / prop for Yup object schemas called validationSchema which will automatically...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Formik sets the field to
undefined
when it’s empty (interesting). So you actually are throwing an error in your validation schema (propertylength
does not exist on undefined). You need to change you condition to look like this:@jtterra, you’re kind of blocked from doing it “properly” by this.
But you can still do it, the thing is, you’re going to recreate your schema every time your state changes, so you don’t actually have a conditional schema per se, but you’re going to recreate your schema every time your state changes. This could be bad for perf (but if you don’t notice anything then it’s fine). In the meantime, keep an eye on the PR I mentioned above.
The way to do this is to put the schema as part of your state, and then update the schema every time
hasNote
changes. In the functional component world it would look like this:and now
FormSchema
looks like this: