jaredpalmer / formik

Build forms in React, without the tears 😭
https://formik.org
Apache License 2.0
33.87k stars 2.79k forks source link

Multiple Field Level validation #2463

Open slava-lu opened 4 years ago

slava-lu commented 4 years ago

🚀 Feature request

there was a request two years ago for multiple Field Level validation

https://github.com/jaredpalmer/formik/issues/682

I find it really a big drawback that I still can't use it.

johnrom commented 4 years ago

My initial thoughts on this.

Redux-Form can offer this functionality because it's built into Redux, which the form library already depends on: https://redux.js.org/api/compose -- it's sort of a "why not?" for redux-form.

For Formik, I don't think it would break backwards compatibility, and it's a very simple feature to add. But it adds maintenance surface to Formik, and I worry it would create different schools of users who want different functionality:

Help! My expensive ajax validate function runs even if the first validation fails! We should make it so that validation only runs until it reaches a failure.

Help! I want to print both error messages when two validations fail, but only one of them runs.

So I recommend letting users handle this functionality. Alternatively, we can expose something like validate={formik.validateAll(required, phone)} or validate={formik.validateAny(required, phone)}. I still think that'd be too limiting as users wouldn't have a choice how to format the combined errors, and returning an array might conflict with how ArrayField works. And at this point, why not just let the user create a validateAll or validateAny function? It's very simple, well described in #682 and here.

slava-lu commented 4 years ago

The solution @johnrom reference is a bit cumbersome. It still requires to have the function per field which is compiled of other functions and you do not have easy visibility of what you test.

The Yup that you recommend is cool, but field level validation is also cool and putting them together would be awesome and redux-forms validation kind of does it. Form level validation add maintenance overhead as you need to keep in mind that if you rename the field name your validation will break. And if your form is long enough you may even miss that is is validated. You remember it when you code but it is easy to be forgotten in 2 yeas or by a new developer. And you really need to validate a field in 99% of all cases. Interdependent fields are very rare case.

BernardA commented 2 years ago

I really do second @slava-lu on this. Just hesitantly leaving redux-form and losing the ability to just do something like this:

  validate={[required, minLength10, maxLength50, isSpace]}

is a bit painful.

Of course, one can find a workaround, but I believe this is such an important feature that leaving it outside the package is not really viable.