0
votes

I'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.

I don't know how to solve this.

Here's a sample code ...

https://codesandbox.io/s/wizardly-frost-sq7fq

1

1 Answers

2
votes

For those of you who are interested, I found out from the "Yup" repo page on Github that Formik sets the field to "undefined" when it is empty ...

https://github.com/jquense/yup/issues/736

So, you would have to do it like this ...

is: value => value && value.length > 0

I updated the code on "Codesandbox" to reflect this.

Also, the error message will only display if the field is touched at the moment, so even if you typed in the "password" field and you haven't touched the "old_password" filed before, the message won't appear. So to avoid that I edited the input component as well to pass a "showErrorOnTouch" prop to control this ...

https://codesandbox.io/s/yup-conditional-validation-with-formik-sq7fq

I hope this can help someone in the future.