jaredpalmer / formik

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

add onValidationFail in <Formik/> #1670

Open xurei opened 5 years ago

xurei commented 5 years ago

πŸš€ Feature request

Context

I'm using Formik with yup for validation. I would like to show an alert when validation fails, but only on submit. I didn't find any easy way to do that.

Current Behavior

Right now the best way I found is to write a custom validate() fucntion that basically reproduce the code in Formik and call a function if an error is found.

<Formik validate={(values) => {
    return (
        validateYupSchema(values, options.validationSchema)
        .then(
            () => {
                return null;
            },
            (err) => {
                // Taken from Formik source code
                if (err.name === 'ValidationError') {
                    const errors = yupToFormErrors(err);

                    // This is the part I added
                    if (props.onValidationFail) {
                        this.showAlertBox('Some fields are invalid');
                    }

                    //Throw errors back to formik
                    throw errors;
                }
                else {
                    // We throw any other errors
                    /* ... */
                }
            }
        )
    }
}>

Desired Behavior

Formik could send an event in case of a validation fail. The context of the validation (submitting or not) should be useful as well.

Suggested Solution

<Formik validationSchema={mySchema} onValidationFails={(errors, formikBag) => {
    this.showAlertBox('Some fields are invalid');
}}>

Who does this impact? Who is this for?

This is mostly useful in conjunction with Yup. A custom validation function can already deal with these cases.

kieranmaine commented 5 years ago

@xurei How did you get this to only fire on the form submit? Using your code it's displaying alerts after onChange and onBlur events.

xurei commented 5 years ago

@kieranmaine Does it matter with the subject ? I mean it could be useful for onChange and onBlur events too...

johnrom commented 5 years ago

@xurei @kieranmaine I think both of these scenarios are perfect candidates for using a Formik Effect, basically creating your own component which listens to formik props and triggers a callback when certain conditions are met. I made an example here:

https://codesandbox.io/s/formik-v2-onvalidationfail-s7zy1

Unfortunately, Formik doesn't always trigger isValidating, so it can't currently be used for onChange or onBlur events. Any thoughts on whether we can/should support something like that @jaredpalmer @Andreyco ?

bombillazo commented 2 years ago

Any update on this? Id like to run a function whenever the form validation fails when I press the submit button, and let it be handled by Formik.