Guides
Last updated
August 4, 2023

How to Validate Forms in React: The Ultimate Guide

Elizabeth (Lizzie) Shipton

Table of Contents:

Get your free
Email Validation
API key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Form validation: love it or hate it (and you probably hate it) it’s an important part of a website or app. Whether you are building a simple webpage or a complicated social media app, you are almost certainly going to have to validate some user input in a form at some point.

Fortunately, these days, there are all kinds of libraries, frameworks, and packages that take a lot of the headache out of building forms. In particular, React JS and its supported libraries make form validation relatively quick and painless.

In this article, we’ll look at what basic form validation entails, and cover some form validation methods available through React JS.

Let’s send your first free
Email Validation
call
See why the best developers build on Abstract
Get your free api

Input Validation 

Input validation is the process of checking that information provided to an application meets expected parameters. It prevents improperly formatted data from entering the database or other information systems. It also helps to prevent malicious users from injecting scripts into the application.

The first line of defense in input validation is client-side validation, which is what we’ll talk about in this article. Performing client-side validation means ensuring that all form fields on the client have been correctly filled out, and properly formatted and that they do not contain any malicious data before the information is sent to the server.

HTML5 Form Validation

The most basic type of client-side form validation uses the built-in HTML5 form controls. These are easy to use and quite performant, but less flexible than custom-built Javascript form validation methods.

HTML5 provides a few form validation rules that you can use to validate user input:

  • required. Specifies whether a form field must be filled in before submitting is allowed.
  • minlength and maxlength. Specify the minimum and maximum length allowed for strings.
  • min and max. Specify the minimum and maximum values allowed for numbers.
  • type: Specifies what type of data is expected (string, number, email address, phone number, etc.)
  • pattern: Specifies that the data needs to match a pattern, denoted by a regular expression.

Let’s look at what HTML5 form validation for an email address might look like.



Here, we’ve used the type validation rules attribute to specify that the form input expects an email and that the form field is required. The input component will raise an error whenever the form is submitted without a valid email address in this form field.

Another way we could validate email input using HTML5 form controls is to provide a Regex pattern that matches email addresses to the pattern validation rules attribute.



Browser Support and Other Caveats

If you intend to use HTML5 form controls to validate email input using validation rules, be aware that it may not be supported by all browsers. Can I Use is a great resource for checking browser support compatibility. Make sure you provide a fallback for browsers that don’t support HTML5 form controls.

HTML5 form controls provide minimal validation for inputs. They do not tell you, for example, whether an input email is a real email address, or provide any level of security.

React Bootstrap

React Bootstrap is one of the oldest React libraries and has evolved alongside React for years now, making it robust and feature-rich. React Bootstrap replaces Bootstrap JS by encapsulating the specs of Bootstrap into reusable React components, eliminating the need for JQuery or other frameworks.

React Bootstrap Form Validation

React Bootstrap provides a React Form component that makes building and validating forms very easy. To use it, import the component into your project.


import Form from 'react-bootstrap/Form';

The component provides access to its child components through dot notation. We’ll access those children to build our complete form.


// component code


Email



// more component code

Notice that the React Bootstrap component gives us access to the same HTML5 form controls that we used before. To update the form state, we’ll use the useState hook and the onChange attribute of the React Form.Control element.


const [ email, setEmail ] = useState('');
const handleUpdateEmail = (e) => {
e.preventDefault();
setEmail(e.target.value);
}



Let’s add a Button to submit our form. If we include our button inside the React Form element and give a type of “submit”, React Bootstrap will automatically handle validating the form data for us.


import Button from "react-bootstrap/Button";
// component code


Email




// more component code

React Bootstrap will raise validation errors if the email Form.Control component is submitted with an invalid email address. You can capture those errors and set them in form state, then display an error message to the user using the isInvalid attribute of the Form component.

React Hook Form Validation

React Hook Form is a performant and easy-to-use library that takes advantage of React Hooks to build forms. It works by registering components to a React hook using a provided register method, and provides a handleSubmit method that validates all form data before calling the onSubmit callback that you provide.

To get started with React Hook Form, import the hook into your file.


import { useForm, form, input } from "react-hook-form";

export default function EmailForm() {
const { register, handleSubmit } = useForm();
const myOnSubmit = data => console.log(data);

return (




);
}

This is all it takes to create a simple email input using React Hook Form. In order to add validation, we can add the required validation parameters to the register function.



As you can see, we’re validating via HTML5 form control methods again. We’ve provided a Regex pattern to the pattern attribute. 

The onSubmit method supplied by React Hook Form will pick up on any validation issues in the form data and raise them as an error. We can capture those errors inside our custom myOnSubmit function, set an error message in the form state, and display it to the user.

React Hooks are a powerful way of using React. If you aren't familiar with React hooks yet, we recommend learning more here.

React Native Validation

Working on mobile with React is very easy if you use React Native. React Native allows you to write familiar React code, then creates a native bridge between the app and the target platform. It allows you to write and run React code on iOS, Android, Android TV, Web, and Windows.

The best part about using React Native is that you can use all the same libraries and frameworks that you would use in a regular React app. Doing form validation in React Native is very similar to doing form validation in React.

You can use React Hook Form and React Bootstrap with React Native. You can also use third-party libraries like Formik and Yup. However, there are some small differences in the way that ReactDom and React Native handle text and form data, so be sure to read the documentation for your chosen solution. 

The library’s docs will tell you whether or not it is supported by React Native, and will include a section on how to use the library with React Native.

This tutorial won’t dive into the specifics of how to get up and running with React Native. For that, we recommend checking out the docs.

Read more about React Native Email Validation or React Native Phone Number Verification.

Third-Party Libraries

There are some great third-party libraries for form validation out there. Some of the best include Formik, React Final Form, react-jsonschema-form, and React Select. Let’s take a quick look at how Formik handles form validation.


import React from "react";
import { Formik, Form, Field } from "formik";

// component code
initialValues={{ email: '' }}
validate={(values) => {
const errors = {};
const validated = await handleValidateEmail(values.email);
if (!validated) {
errors.email = 'Invalid email';
} else {
errors.email = ''
console.log("SUBMITTED! ", values.email);
}
return errors;
}}
onSubmit={(values) => {console.log(values)}}
>
{({
handleSubmit,
errors
}) => (


{errors.email && (
{errors.email}
)}


)}

// more component code

Formik provides a Form component that handles rendering, along with a Formik controller that handles logic. Inside the Formik controller, we provide the form with initial values, an onSubmit handler, and a validate function. 

Inside the validate function, we create an errors object and define custom error messages for each validation error. We then return the errors object to the Formik controller. The controller passes down our errors object, along with our custom onSubmit handler to the rendered component, where we can access the validation errors and display them to the user.

In this case, the validate function will be called on every keystroke, not only on submit. If you’d prefer to have the validation only happen on submit, you can eliminate the validate prop and handle validation inside your onSubmit handler.

Email Validation Through an API

Validating emails using the HTML5 form components is fine, but it won’t give you any information about the email. Additional information you might want to learn about an email could include whether or not the email is currently active, and whether it can be delivered to. 

If you want more information about the email addresses your users are entering, you’ll need to validate the emails through a dedicated email validation API. Let’s take a look at one such API—AbstractAPI’s Free Email Validation API.

Acquire an API Key

You’ll need an API Key to use the Abstract API. All Abstract APIs have unique keys, so even if you’ve used the API before, you’ll need a separate key for this endpoint.

To get one, navigate to the API Get Started page. You’ll see an example of the API’s JSON response object, and a blue “Get Started” button on the left. Click “Get Started.”

If you’ve never used AbstractAPI before, You’ll need to input your email and create a password. If you have used Abstract before, you may need to log in.

Once you’ve logged in, you’ll land on the API’s homepage. You’ll see options for documentation, pricing, and support, and you’ll see your API key.

Send a Request to the Abstract Endpoint

Using your preferred HTTP client, send a GET request to the Abstract API Email Validator. The request must include your API key and the email to be validated.


import axios from "axios";

const apiKey = YOUR API KEY;
const apiURL = 'https://emailvalidation.abstractapi.com/v1/?api_key=' + apiKey

const sendEmailValidationRequest = async (email) => {
try {
const response = await axios.get(apiURL + '&email=' + email);
return response.data.is_valid_format.value
} catch (error) {
throw error;
}
}

You’ll get back a JSON response that looks something like this:


{
"email": "[email protected]",
"autocorrect": "",
"deliverability": "DELIVERABLE",
"quality_score": "0.80",
"is_valid_format": {
"value": true,
"text": "TRUE"
},
"is_free_email": {
"value": false,
"text": "FALSE"
},
"is_disposable_email": {
"value": false,
"text": "FALSE"
},
"is_role_email": {
"value": false,
"text": "FALSE"
},
"is_catchall_email": {
"value": true,
"text": "TRUE"
},
"is_mx_found": {
"value": true,
"text": "TRUE"
},
"is_smtp_valid": {
"value": true,
"text": "TRUE"
}
}

Use the Validation Response

All of this information can now be used in your React app, or sent to the server to be added to a database. For the purposes of client-side validation, we can just pull the is_valid_format.value boolean out and return it as the result of our validation function.

This step in the validation process can be incorporated into React Hook Form, Boostrap, or any of the methods we previously looked at. For example, when performing email form validation with Formik, you can include a call to the Abstract API endpoint as a step in the function that you provide to the controller’s validate attribute.

Conclusion

Email form validation doesn’t have to be a headache. The days of writing thousands of lines of boilerplate code just to build a simple form input are over. React Bootstrap, React Hook Form, React Native, and third-party libraries like Formik and React-Select make building and validating a form straighforward and efficient.

For an additional layer of validation, incorporate an email validation API like AbstractAPI’s Free Email Validation API into any of the methods we studied in this tutorial.

FAQs

How do I verify my email in React Native?

Verifying an email in React Native is almost the same as verifying an email in React. React Native is purpose-built to provide the same APIs that you’re familiar with, and to work with the same libraries that you already use with React.

There are a few differences in how React Native and ReactDOM handle text inputs, so be sure to read the documentation for whichever library you are using with React Native to familiarize yourself with the parameters.

How do I verify an email address with React Hook Form?

React Hook Form provides a handleSubmit method that runs validation at the time the form is submitted. Pass the handleSubmit method to the onSubmit prop on the Form component. The method accepts one argument, your custom onSubmit function. This function will be called after React Hook Form finishes validating all the inputs.

What is email validation?

Email validation is the process of checking that the email a user provides is formatted correctly. A valid email contains a string, followed by the ‘@’ symbol, followed by a top-level domain like ‘.com’ or ‘.org.’ Proper email validation checks that all the elements are present, and also checks that there are no unexpected characters or malicious scripts input into the field.

Take email validation a step further by checking whether the email is currently active and accepting messages. To perform this level of validation, you’ll need to use a validation service like AbstractAPI.

Elizabeth (Lizzie) Shipton

Lizzie Shipton is an adept Full Stack Developer, skilled in JavaScript, React, Node.js, and GraphQL, with a talent for creating scalable, seamless web applications. Her expertise spans both frontend and backend development, ensuring innovative and efficient solutions.

Get your free
Email Validation
key now
See why the best developers build on Abstract
get started for free

Related Articles

Get your free
Email Validation
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required