Input Validation in React Hook Form & sending emails using EmailJS in ReactJS

Charlie K
4 min readFeb 4, 2022

Serverless Email Sending from your Contact Form

Forms are one of the most widely used ways of getting data from a user on any website. To ensure a better user experience, form validation is essential before the user clicks on that ‘Submit’ button.

In this article, we will take a look at how to add form validation on the client-side using React Hooks Form and send an email directly when user submits the form using EmailJS.

Using EmailJS we can send an email from our Contact Form without a backend.

React Hook Form and EmailJS

Lets get started

Firstly let’s set up the react web app. Use npm to create default app

npx create-react-app react-formvalidator-emailjs
cd react-formvalidator-emailjs

We will be using the following dependencies so let’s install them

npm i react-hook-form @hookform/resolvers bootstrap computed-types emailjs-com email-validator
  1. Creating the Contact Form:

Using bootstrap let’s create the contact form:

Contact Page with contact form

Now we need to import EmailJS and setup the schema. For our form we expect to get name, email, subject and message.

import * as EmailValidator from 'email-validator';import { computedTypesResolver } from '@hookform/resolvers/computed-types'import { useForm } from 'react-hook-form';import Schema, {string} from 'computed-types';//....
//validate Email function Email(input: unknown): string { if (!EmailValidator.validate(String(input))) { throw new TypeError(`Invalid email address: "${input}"`); } return input; }// create a schema for input fieldsconst schema = Schema({ name: string.min(1).error('Name field is required'), email: Email, message: string.min(1).error('message field is required'), subject: string.min(1).error('subject field is required'),});

For the email field we use email-validator to validate the email as seen in the Email function above.

2. Input Validation

The useForm Hook returns an object containing a few properties. For now we only require register and handleSubmit

const { register, handleSubmit, formState: {errors},} = useForm({     resolver: computedTypesResolver(schema)});

The register method helps us register an input field into React Hook Form so that its available for validation and its value can be tracked for changes.

To register the input, we pass the register method into the input field as shown:

Input with validation errors

The p element is used to show errors incase input from user fails the validation. For each field there will be a corresponding p tag to indicate to user to validate their input.

Input validation in the Contact form

3. Setting up EmailJS

We need to create an account with EmailJS and login.

On the ‘Email Services’ tab we click to add a new service. We pick Gmail as our Email service.

Configure Gmail email service

Next create an Email Template under ‘Emails Template Tab’.

Note‼ : The fields in the template should match the fields in the schema

Email Template

Finally you can configure auto-reply to reply to the sender when they submit the form to inform them that you have received their response.

Auto-reply EmailJS

By creating a default template we can now be able to send Emails using EmailJS. However we will need the SERVICE_ID , TEMPLATE_ID and USER_ID . This can be gotten from the dashboard. These details are stored as environment variable in .env file.

To send email we well call emailJs.send method that will also require templateParams which is just the parameters in the contact-form. For this we will create an object and store the form parameters.

Finally we create our sendEmail method that sends an Email and is called when user submits the form.

SendEmail function

4. Testing it all out ✔

At the end this is how your App component should look like:

Click to fork the Github Repo and try it out!

Download and run the app using the command npm run start . Once you fill the form and click on submit button, check your Gmail📨 inbox.

Email Sent successfully

And you are done! Now you can send emails directly from React. 🎉

Remember that EmailJS gives you 200 Emails per month on free-tier. Avoid spamming.

Happy Coding 👨‍💻💡!

--

--

Charlie K

learn, innovate repeat. Writer, web developer ,tech & nature enthusiast. My posts are abstract😜