Guides
Last updated
March 31, 2024

React Native Email Validation (Updated for 2024)

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

These days, email validation is a crucial component of any React app. Whether you are collecting users’ emails for login purposes, for notifications, or for communication and marketing, at some point you will need to validate an email for a user.

Luckily, if you’re using React Native to develop your mobile app, email validation is very easy. React Native allows you to build cross-platform mobile apps using the React JS code that you already know and love. It’s pretty easy to get up and running, and the best part is you can use many of the same libraries that you would use to build a React app.

This article will explore how to set up a basic email form with validation in React Native. We'll build a React app running on iOS, using Native Components and a dedicated email validation API from AbstractAPI.

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

Getting Started With Email Validation in React Native

This article assumes that you are already familiar with React JS, and that you know enough about React Native development to spin up a basic React Native app.

If you’re not, familiar with React JS, we recommend checking out the ReactJS docs to get started.

If you're unfamiliar with React Native, we recommend using Expo to get started with React Native. Think of Expo like Create React App for React Native. It provides the scaffolding you need to get a React Native dev environment up and running quickly.

Spin up your React Native app using the Expo command-line interface. This is like running npx create-react-app for a regular React JS app.


$ expo init react-native-email-validation
$ cd react-native-email-validation

No need to install any additional packages. We’ll be working with Native Components, which are part of the React Native Core library. You will, however, need access to an iOS device running the Expo Go app. Again, this tutorial won’t dive into specifics of how to get started with Expo—for more detail on that, check out the Expo docs.

To check that things are working, let’s start up the app.


$ expo start

This command tells Expo to start the Metro bundler, which compiles and bundles the code and serves it to the Expo Go app. Open up the Expo Go app on your phone to connect to the Metro bundler and view the new app.

That’s all we need to do to get our new React Native app up and running!

Building a React Email Form With Native Components

Create the EmailForm Component

Create a new file next to App.js called EmailForm.js. This is the file that will contain all the logic for our email form and will render the form component. Inside it, create an EmailForm React component that renders a simple, single-input email form. It will be very similar to a React JS component.


import React, { useState } from "react";
import { TextInput, SafeAreaView, StyleSheet, Text, TouchableHighlight } from "react-native";
const EmailForm = () => {
const [email, setEmail] = useState("");
const handleSubmit = () => {
// write this next
}
return (

onChangeText={(e) => setEmail(e.target.value)}
value={email}
/>

Submit


)
}
const styles = StyleSheet.create({
emailInput: {
width: 250,
height: 25,
borderWidth: 1,
borderColor: 'black',
},
button: {
borderWidth: 1,
borderColor: 'green',
borderRadius: 15,
marginTop: 25,
padding: 10,
alignItems: 'center'
},
});
export default EmailForm;

We’ve set the initial email state to an empty string using the useState hook, and passed that to the TextInput component as the value prop. Next, we told onChangeText to update the state of the email to the inputted value, and we scaffolded out a handleSubmit function that will be called when the user taps the “Submit” button.

We’ve also placed the form inside the SafeAreaView component to make sure it renders in the correct place on the mobile screen, and we’ve added some styles using the StyleSheet component to make it a bit more visually appealing.

Next, we’ll write the handleSubmit function, which will validate the email input before submitting it.

Add Validation Logic

Our handleSubmit function will take the provided email as its input, send the email to the AbstractAPI Email Validation endpoint for validation, and then—as long as validation is successful—submit the email to our server. 

For now, rather than submitting it to the server, we’re just going to log the email to the console. Let’s take a look at the AbstractAPI endpoint that will do the actual validation.

Get Started With the API

Acquire an API Key

Go to the Email Validation API Get Started page. You’ll see an example of the API’s JSON response object. Click the blue “Get Started” button.

Once you’ve signed up or logged in, you’ll be taken to the API’s homepage. You should see options for documentation, pricing, and support, and you’ll see your API key. 

All Abstract APIs have unique keys, so even if you’ve used the API before, this key will be unique. Don’t attempt to use a different AbstractAPI key with the Email API—it won’t work.

Send a Request to the API

React Native uses the Fetch API to send and receive HTTP requests. 

Let’s write a function called sendEmailValidationRequest to send the request to the API using Fetch.


const apiKey = 'YOUR_API_KEY';
const apiURL = 'https://emailvalidation.abstractapi.com/v1/' + apiKey;
...
const sendEmailValidationRequest = async (email) => {
try {
const response = await fetch.get(apiURL + '&email=' + email);
console.log(response.json())
} catch (error) {
throw error;
}
}

Don’t forget to call .json() on the response to parse it correctly. The response data will look something like this:


{
"email": "eric@abstractapi.com",
"autocorrect": "",
"deliverability": "DELIVERABLE",
"quality_score": "0.80",
"is_valid_format": {
"value": true,
"text": "TRUE"
},
...
}

There’s a lot more information in this object that has been omitted here. The part we’re interested in for now is the is_valid_format field. Let’s return the value boolean from that field so that our validation function can use it.


const response = await fetch.get(apiURL + '&email=' + email);
const data = response.json();
return data.is_valid_format.value;

Use the Response in the Submit Function

Now that we have our response from the API, let’s use it in our handleSubmit function. Before the console.log(email) line, add a call to the sendValidationRequest function. Next, use the response to decide whether to submit the valid email, or reject it.


const handleSubmit = async (email) => {
const isValid = await sendEmailValidationRequest(email);
if (isValid) {
console.log("SUBMITTED! ", email);
} else {
console.log("EMAIL WAS INVALID.");
}
return isValid;
}


Render the Form in App.js

Delete all the boilerplate between the outermost <div> elements in App.js. Import your new email form and render that React component instead.


import { StatusBar } from 'expo-status-bar';
import { StyleSheet, View } from 'react-native';
import EmailForm from './EmailForm';

export default function App() {
return (




);
}

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});


Visit the Expo Go app again. Your new form should be rendered!

Error Handling

Let’s add some error handling to the handleSubmit function. We’ll create a value in state to hold an error message string in the case that validation fails. When validation fails, we’ll set the error message into state and use a Native Component Text element to display it to the user. 


const [errorMessage, setErrorMessage] = useState("");
...
const handleSubmit = async (email) => {
try {
const isValid = await sendEmailValidationRequest(email);
if (isValid) {
setErrorMessage("");
console.log("SUBMITTED! ", email);
} else {
setErrorMessage("INVALID EMAIL.PLEASE CHECK YOUR INPUT AND TRY AGAIN.");
console.log("EMAIL WAS INVALID.");
}
return isValid;
} catch (error) {
setErrorMessage("SOMETHING WENT WRONG.PLEASE TRY AGAIN LATER.");
}
}
...
{errorMessage}

As you can see, we added a bit more code around the async/await request. This validation method requires an API call, which could fail for any number of reasons beyond our control. We wrapped the HTTP request in a try/catch block so that if any errors arise while making the HTTP request, we can catch those and also display and error message to our user.

Put it All Together

Let’s take a look at the complete code for our EmailForm React component, including error handling.


import React, { useState } from "react";
import { TextInput, SafeAreaView, TouchableHighlight, Text, StyleSheet } from "react-native";

const apiKey = 'YOUR_API_KEY';
const apiURL = 'https://emailvalidation.abstractapi.com/v1/' + apiKey
const EmailForm = () => {
const [email, setEmail] = useState("");
const [errorMessage, setErrorMessage] = useState("");

const sendEmailValidationRequest = async (email) => {
try {
const response = await fetch.get(apiURL + '&email=' + email);
const data = response.json();
return data.is_valid_format.value;
} catch (error) {
throw error;
}
}
const handleSubmit = async (email) => {
try {
const isValid = await sendEmailValidationRequest(email);
if (isValid) {
setErrorMessage("");
console.log("SUBMITTED! ", email);
} else {
setErrorMessage("INVALID EMAIL.PLEASE CHECK YOUR INPUT AND TRY AGAIN.");
console.log("EMAIL WAS INVALID.", email);
}
return isValid;
} catch (error) {
setErrorMessage("SOMETHING WENT WRONG.PLEASE TRY AGAIN LATER.");
}
}
return (

style={styles.emailInput}
onChangeText={(e) => setEmail(e.target.value)}
value={email}
/>

Submit

{errorMessage}

)
}
const styles = StyleSheet.create({
emailInput: {
width: 250,
height: 25,
borderWidth: 1,
borderColor: 'black',
},
button: {
borderWidth: 1,
borderColor: 'green',
borderRadius: 15,
marginTop: 25,
padding: 10,
alignItems: 'center'
},
});

export default EmailForm;

Type an invalid email address into the input and click “Submit.” When the API response returns from AbstractAPI, you should see an error message pop up telling you that the email is invalid.

Conclusion

This is a great start to a simple email input form with validation and error handling!

To further improve the user experience of this form, we could add a loading spinner and disable the “Submit” button after the user taps it to prevent multiple submissions and to let the user know that their request is processing.

React Native and Expo are awesome tools for getting iOS and Android apps up and running quickly, and for doing email validation in React Native. 

FAQs

What is React Native?

React Native is a JavaScript framework that helps developers write native mobile applications using React. React Native works by spinning up threads that interpret JavaScript code, then creating a native bridge between the React JS code and the native target platform. The React JS component hierarchy is then transferred to the mobile device view.

How Do I Validate Email in React Native?

The easiest way to do email validation in React Native is to create a simple email input form using the Native Components TextInput component. The TextInput accepts user input, which can then be stored in state as an email address. The TouchableHighlight component can then be used to create a button that runs a custom validation function against the email address before submitting it to the server.

There are many ways to write a validation function. You could match the email string against a RegEx pattern to check that it is formatted properly. You could use a third-party validation library like react-email-validator, or you could use a dedicated third-party email validation API like AbstractAPI’s Free Email Validation API.

How Do You Validate TextInput Values in React Native?

The easiest way to do TextInput validation in React Native is to run the input through a validation function when the onSubmit handler is called for your form. You can either test the input against a RegEx pattern, against a pre-defined custom schema, or against some library or API endpoint to check that the input is well-formed and correct.

If you want to validate the input before the “Submit” button is pressed, call the validation function in the onBlur or onChange handler. onBlur will call the validation function when the user taps away from the input. onChange will call the validation function on every keystroke as the user inputs text into the TextInput.

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