Skip to content
Advertisement

Perform function after form validation

I am using react, typescript, and Email JS library. I am using the react-hook-form library and yup to validate forms.

I have worked out the validation and sending the email, but I am unable to do both these functions together. When a user submits the form, I want the “sendEmail” function to be called if the “handleSubmit(onSubmit)” function which validates the form is successful.

The form’s ‘onSubmit’ property needs to be changed so that both of these can be called. Currently I can call these individually with ‘onSubmit={sendEmail}’ or ‘onSubmit={handleSubmit(onSubmit)}’ and they will work.

What I tried was to put the expression ‘handleSubmit(onSubmit)’ inside the sendEmail function but validation did not work then.

I have also used react-hook-form library.

import React, { useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { string, number, object, InferType } from "yup";
import { url } from "inspector";
import emailjs from "@emailjs/browser";

function onSubmit(values: Props) {}

type Props = InferType<typeof schema>;

const schema = object({
  firstName: string().required("First name is required"),
  lastName: string().required("Last name is required"),
});

function FormEmail() {
  const form = useRef(null);
  const [value, setValue] = useState<string | undefined>();

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<Props>({
    resolver: yupResolver(schema),
  });

  const sendEmail = (e: { preventDefault: () => void }) => {
    handleSubmit(onSubmit)();
    e.preventDefault();

    emailjs
      .sendForm(
       'YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', form.current!, 'YOUR_PUBLIC_KEY'
      )
      .then(
        (result: { text: any }) => {
          console.log(result.text);
        },
        (error: { text: any }) => {
          console.log(error.text);
        }
      );
  };

return (
    <div>
      <form onSubmit={handleSubmit(onSubmit)} ref={form}>

            <h3>First Name</h3>
            <input
              id="firstName"
              type="text"
              {...register("firstName")}
            />
            <span className="error">{errors?.firstName?.message}</span>

            <h3>Last Name</h3>
            <input
              id="lastName"
              type="text"
              {...register("lastName")}
            />
            <span className="error">{errors?.lastName?.message}</span>

            <button className="" type="submit">
              Submit
            </button>
      </form>
    </div>
  );
}

export default FormEmail;


Advertisement

Answer

As stated in the doc, if you want to call onSumbit remotely you need to write it like this:

handleSubmit(onSubmit)();
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement