Home > database >  Form validation using React, EmailJS and Bootstrap
Form validation using React, EmailJS and Bootstrap

Time:08-12

So I'm trying to get my form validation to work using EmailJs and Bootstrap within React for a simple contact form. I got the validation to work on the UI, however, it will still send the email even if the fields are red and required. Any idea what I'm doing wrong? I followed the examples here: https://react-bootstrap.github.io/forms/validation/ and here: https://www.emailjs.com/docs/examples/reactjs/ but it does not seem to be working correctly.

EDIT:

import React, { useRef, useState } from "react";
import emailjs from "@emailjs/browser";
import Button from "react-bootstrap/Button";
import PageTitle from "../components/PageTitle";
import Form from "react-bootstrap/Form";
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import FloatingLabel from "react-bootstrap/FloatingLabel";

import config from "../configData.json";

import "./Contact.scss";

export const Contact = () => {
  const [validated, setValidated] = useState(false);
  const form = useRef();

  const sendEmail = (e) => {
    e.preventDefault();

    emailjs
      .sendForm(
        config.serviceId,
        config.templateId,
        "#contact-form",
        config.publicKey
      )
      .then(
        () => {
          alert("Your message has been sent.");
        },
        (error) => {
          alert("There was a problem sending your message.", error);
        }
      );
    e.target.reset();
  };

  const handleSubmit = (event) => {
    const form = event.target;
    if (form.checkValidity() === false) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      // alert("Message was sent!");
      sendEmail(event);
    }
    setValidated(true);
  };

  return (
    <>
      <PageTitle title="Contact" />
      <div className="container my-5">
        <h2 className="mb-4">Leave a Message</h2>
        <Form
          noValidate
          ref={form}
          onSubmit={handleSubmit}
          validated={validated}
          id="contact-form"
        >
          <Row>
            <Form.Group as={Col} md="12" controlId="nameValidation">
              <FloatingLabel
                controlId="floatingInput"
                label="Name"
                className="mb-3"
              >
                <Form.Control
                  type="text"
                  placeholder="Name"
                  name="user_name"
                  size="lg"
                  required
                />
                <Form.Control.Feedback type="invalid">
                  Please enter your name.
                </Form.Control.Feedback>
                <Form.Control.Feedback>Looks good!</Form.Control.Feedback>
              </FloatingLabel>
            </Form.Group>
            <Form.Group as={Col} md="12" controlId="emailValidation">
              <FloatingLabel
                controlId="floatingInput"
                label="Email"
                className="mb-3"
              >
                <Form.Control
                  type="email"
                  placeholder="[email protected]"
                  name="user_email"
                  size="lg"
                  required
                />
                <Form.Control.Feedback type="invalid">
                  Please enter a valid email.
                </Form.Control.Feedback>
                <Form.Control.Feedback>Looks good!</Form.Control.Feedback>
              </FloatingLabel>
            </Form.Group>
            <Form.Group as={Col} md="12" controlId="messageValidation">
              <FloatingLabel
                controlId="floatingInput"
                label="Message"
                className="mb-3"
              >
                <Form.Control
                  placeholder="Message"
                  name="user_message"
                  size="lg"
                  required
                  as="textarea"
                  rows={3}
                />
                <Form.Control.Feedback type="invalid">
                  Please enter a message.
                </Form.Control.Feedback>
                <Form.Control.Feedback>Looks good!</Form.Control.Feedback>
              </FloatingLabel>
            </Form.Group>
          </Row>
          <Button
            type="submit"
            value="Send"
            variant="primary"
            size="lg"
            className="mt-3 w-100"
          >
            SEND
          </Button>
        </Form>
      </div>
    </>
  );
};

export default Contact;

Thanks in advance for any help you can provide.

CodePudding user response:

Could you please share your HTML where you are getting this info? Even required, you can make the type='email' required so it will validade for you.

if that still a problem (which should not be), then make an IF to validade for you.

CodePudding user response:

I was able to solve this using handleSubmit function with if/else statement. However, after the user submits, the form clears all inputs, re-validates and turns all fields red. Anyway to reset the form back to the original state after submit? I tried using event.target.reset(); but it did not work. Any help here would be greatly appreciated.

const handleSubmit = (event) => {
    const form = event.target;
    if (form.checkValidity() === false) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      // alert("Message was sent!");
      sendEmail(event);
    }
    setValidated(true);
  };
  • Related