Ensuring email addresses are valid is a key part of building any React Native application, preventing bad data and user frustration. We'll walk through five different implementation methods using code examples, examine the common drawbacks of each, and then look at how Abstract API overcomes these limitations.
Email Validation Methods in React Native
Here are three common ways to check email formats directly within your React Native application. Each method operates on the client-side, with different levels of abstraction and setup.
Manual Regex in the Component
This approach uses a controlled TextInput component. A regular expression evaluates the input every time the text field mutates, which provides immediate feedback to the user on the client-side.
For production environments, it is best to use an RFC 5322-level pattern. This type of pattern covers more complex cases like quoted strings, domain-literals, and unusual characters in the local-part of the email.
The code uses React's useState hook to manage the email input and its validity. The emailPattern constant holds the regex, and the onChange function updates the state after each keystroke.
const [email, setEmail] = useState('');
const [valid, setValid] = useState(false);
const emailPattern =
/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/i;
const onChange = txt => {
setEmail(txt);
setValid(emailPattern.test(txt.trim()));
};
Validation with validator.js
The validator.js library offers an isEmail helper function. This function encapsulates a well-maintained regex and includes flags for dozens of edge cases, which removes the need to manage the pattern yourself.
You can add it to your project with npm i validator. After tree-shaking, its bundle size is approximately 21 KB. The check is a pure function, so you can memoize it.
The code imports the isEmail function and calls it inside the onChange handler. You can pass an options object to customize validation, such as to disallow UTF8 characters or require a top-level domain.
import isEmail from 'validator/lib/isEmail';
const onChange = txt => {
setEmail(txt);
setValid(isEmail(txt, { allow_utf8_local_part: false, require_tld: true }));
};
Formik and Yup Schema Validation
This method combines two libraries. Formik handles form state and logic, while Yup provides a declarative way to define a validation schema. Yup comes with a pre-built email() method for this purpose.
Validation can fire on different events, like a text change or when the input loses focus. Formik then propagates any validation errors through its props, which you can use to display feedback.
The code defines a schema with Yup. The Formik component wraps your input, connects the schema, and provides helper props like handleChange and values to link the TextInput to the form state.
A key benefit is that the schema is portable. You can share the same validation logic between your mobile and web applications to prevent any drift in rules.
import { Formik } from 'formik';
import * as Yup from 'yup';
const schema = Yup.object({
email: Yup.string().email('Invalid').required('Required')
});
<Formik initialValues={{ email: '' }}
validationSchema={schema}>
{({ handleChange, values, errors, touched }) => (
<TextInput
value={values.email}
onChangeText={handleChange('email')}
/>
)}
</Formik>
Challenges of Client-Side Validation
Client-side validation provides instant feedback but introduces platform-specific bugs and format limitations. These methods cannot confirm if an email address is actually real, only that its syntax appears correct.
- Manual regex patterns struggle with official email standards. They either accept invalid formats or become too complex to maintain. This affects the manual regex method and libraries like Yup that rely on them.
- Regex engines differ across platforms. A pattern that works on iOS might fail on an updated Android device. This creates unpredictable behavior for the same React Native code, especially with manual regex implementations.
- Native device keyboards and text inputs can cause crashes. For example, some predictive text features freeze the UI when validation logic re-renders the component frequently, a common issue with controlled inputs.
- Format checks from regex, validator.js, or Yup cannot detect typos or dead domains. They approve syntactically correct but undeliverable addresses because they do not check mail server records.
Validate Emails with Abstract API
Ensure data integrity in your React Native app by implementing effective email validation.
Get started for free
How Abstract API Handles Email Validation in React Native
Traditional methods like regex validation often fail because they only check syntax. They cannot tell if a domain exists or if a mailbox accepts mail. Abstract API addresses these core weaknesses by offloading complex checks to a dedicated network service.
- It performs RFC-5322 syntax analysis, backed by machine learning for edge-case coverage.
- It executes real-time DNS MX and SMTP handshakes to prove an email address has deliverability.
- It detects disposable, role-based, free-provider, and catch-all domains with more than 3,000 curated lists.
- It provides typo autocorrection suggestions and a quality score so you can set your own accept or deny threshold.
How to Add Abstract API to Your Dev Environment
Once you understand Abstract’s capabilities, you can add its email validation API to your project with ease.
- Sign up at Abstract API, create a workspace, and copy your unique API key.
- Create a service file, such as emailService.js, and store the key in an environment variable or secrets manager.
- Build a helper function to communicate with the API endpoint.
- Call the validation function from your form’s submit handler to block, warn, or autocorrect based on the response.
- Add retry logic and cache positive results to improve performance and reduce quota use.
const apiKey = process.env.ABSTRACT_KEY;
const endpoint = 'https://emailvalidation.abstractapi.com/v1/';
export async function validateEmail(email) {
const url = `${endpoint}?api_key=${apiKey}&email=${encodeURIComponent(email)}`;
const res = await fetch(url);
if (!res.ok) throw new Error('Abstract error');
return res.json();
}
Sample Email Validation with Abstract API
The helper function above sends a simple HTTPS request to the Abstract API endpoint with a user's email. The API then returns a detailed JSON object. This response provides a clear allow or deny decision based on multiple factors like deliverability, domain checks, and a quality score.
For example, a request for "eric@abstractapi.com" produces the following output. The "DELIVERABLE" status, high quality score, and "TRUE" values for MX and SMTP checks confirm the address is safe to accept.
{
"email": "eric@abstractapi.com",
"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_mx_found": { "value": true, "text": "TRUE" },
"is_smtp_valid": { "value": true, "text": "TRUE" }
}
Final Thoughts
Traditional regex checks only cover syntax and cannot confirm if an email address actually works. This gap leads to bounces and poor data quality. Abstract API overcomes these issues through real-time SMTP handshakes and comprehensive domain analysis. To reliably validate user emails, consider an account on Abstract API to get your free API key.
Validate Emails with Abstract API
Implement proper email validation in your React Native app to prevent invalid user entries.
Get started for free