shayanvalaie
shayanvalaie

Reputation: 61

Error while creating validations for react-hook-form

I am trying to create validations for my react-hook-form but when I go try to display the errors on the front end I receive this error.

× TypeError: Cannot read properties of undefined (reading 'name')

It seems like everything is working until I try to display it with the following code

{errors.name && errors.name.message}

import emailjs from "emailjs-com";
import { useForm } from "react-hook-form";









const Contact = () => {
    const [successMessage, setSuccessMessage] = useState("");
    const { register, handleSubmit, errors } = useForm();


    const serviceID = "s_ID";
    const templateID = "t_ID";
    const userID = "user_12345";

    const onSubmit = (data, r) => {
        sendEmail(
            serviceID,
            templateID,
            {
                name: data.name,
                email: data.email,
                subject: data.subject,
                description: data.description,
            },
            userID
        )
        r.target.reset();
    }

    const sendEmail = (serviceID, templateID, variables, userID) => {
        emailjs.send(serviceID, templateID, variables, userID)
            .then(() => {
                setSuccessMessage("Form sent successfully! I'll contact you as soon as possible");
            }).catch(err => console.error(`Something went wrong ${err}`));
    };

    return (
        <div className="contacts">
            <div className="text-center">
                <h1 className="bold upper-case">contact me</h1>

            </div>
            <div className="container">

                <form onSubmit={handleSubmit(onSubmit)}>

                    <div className="row">

                        <div className="col-md-6 col-xs-12">

                            {/* Name Input */}
                            <input type="text" className="form-control" placeholder="Name" name="name"
                                {
                                ...register("name", {
                                    required: "Please enter your name",
                                    maxLength: {
                                        value: 20,
                                        message: "Name must not be longer than 20 characters",
                                    }
                                })
                                } />

                            <span className="error-message">
                                <p> {errors.name && errors.name.message} </p>
                            </span>





                            {/* Email Input */}
                            <input type="email" className="form-control" placeholder="E-mail" name="email" />

                            {/* Subject Input */}
                            <input type="text" className="form-control" placeholder="Subject" name="subject" />
                        </div>
                        <div className="col-md-6 col-xs-12">
                            {/* Subject Input */}
                            <textarea type="text" className="form-control" placeholder="Subject" name="description" />
                            <div className="text-center center">
                                <button className="btn btn-outline-dark contact-button p-button mt-3" type="submit">
                                    Send!
                                </button>
                            </div>

                        </div>

                    </div>
                </form>

            </div >

        </div >
    )
}

export default Contact

Upvotes: 0

Views: 700

Answers (1)

Jae
Jae

Reputation: 116

Your code helped me debug my EmailJS submission so it's only right if I try my best to help you.

I'm able to successfully display my validation error messages by doing the following:

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<IContactForm>();


.
.
.
<form>
 <input {...register("firstName", { required: "ENTER YOUR FIRST NAME" })}/>
 {errors.firstName && errors.firstName.message}
</form>

Only difference I see is that you don't have 'formState: {errors}' for your useForm hook.

Upvotes: 2

Related Questions