Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

form is not posting using react handleSubmit hook

I am trying to post this form to my mongoDB. When I just use onSubmit={true} the form posts just like I want. However, when I use the following code and return true the form does not post and I don’t know why.

const handleSubmit = (e) => {
        e.preventDefault();
        let password = e.target.password.value;
        let confirmPassword = e.target.confirmPassword.value;
        let email = e.target.email.value;
        let emailRegex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

        // set up email regex. and regex for valid names.
        if (!emailRegex.test(email)) {
            setError(true)
            setErrorMessage("invalid email address.");
            return false;
        }
        if (password !== confirmPassword) {
            setError(true)
            setErrorMessage("passwords do not match.");
            return false;
        }
        setError(false)
        console.log("reached end")
        return true;
    }

This is the handleSubmit function. When I take away e.preventDefault() the form posts but does not have any of the validations I want to do first.

Also I have a console.log("reached") at the end of the function that always shows and return true; right after it. Thus, the function should return true and form should post.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<Form id="registerForm" onSubmit={handleSubmit} method="POST" action="http://localhost:4000/api/auth/register">

//inputs

</Form>

Again when I replace handleSubmit with the boolean variable true everything works as planned. I also tried onSubmit={(e) => handleSubmit(e)} but get the same problem.

Can anyone help?

>Solution :

This happens because you’re calling e.preventDefault(); in your submit function, which prevents the default submit action from firing. So your form is going through validation but then never submits.

To submit the form, add e.target.submit() at the end of your handleSubmit method.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading