Skip to content Skip to sidebar Skip to footer

Unable To Set Errors In Formik Onsubmit

I'm having some issues for a couple days now where every error that I set in the onSubmit method of my Formik form are not added to the errors props. My specific issue is concernin

Solution 1:

I had been working on this the whole day by now, and finally, I resolved it.

If you setFieldError and then the validation function is executed, those errors are overwritten. I don't know if this is the best solution, but for me is working.

constvalidate = (values) => {
        // let prevErr = formik.errors;const errors = {};
        console.log("inside validate", formik);
        if (!values.email) {
            if (!formik.errors.email) {
                errors.email = "Required";
            } else {
                errors.email = formik.errors.email;
            }
        } elseif (
            !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)
        ) {
            errors.email = "Invalid email address";
        }

        if (!values.password) {
            if (!formik.errors.email) {
                errors.password = "Required";
            } else {
                errors.password = formik.errors.password;
            }
        }

        return errors;
    };
constonError = (data) => {
        formik.setFieldError("email", "BackEnd Error");
        formik.setFieldError("password", "BackEnd Error");
    };

Things to try looking for your solution:

  • Initial values, must be setted
  • Console.log the form inside the validation function to see when the errors that you set are loaded on the form.
  • Take a look if the fields are touched
  • Maybe the validation function is executed more than two times and this end up overriding those errors because they are no longer there.

Let me know if any of this works, this is my first time posting a solution on Stack Overflow.

Thanks!

Post a Comment for "Unable To Set Errors In Formik Onsubmit"