Ensuring user emails are valid is a key part of building reliable Flutter applications. This piece walks through five ways to handle email validation, providing working code for each. We then examine the shortfalls of these common techniques and show how Abstract API overcomes them.
How to Implement Email Validation in Flutter
Here are three common, client-side methods to validate email syntax directly within a Flutter application. Each approach offers a different balance of simplicity, control, and dependency management.
Inline Regular Expression
This pure Dart approach keeps validation stateless and client-side. It involves the creation of a validator from a regular expression pattern that follows the RFC 5322 standard for email syntax. This pattern checks for the correct structure of an email address.
The code defines a global `RegExp` object with the validation pattern. A function then uses this object's `hasMatch` method to check if an input string is a valid email. This function can be passed directly to a `TextFormField` widget's validator property.
final _emailRe = RegExp(
r'''^(?:(?:[^<>()\[\]\\.,;:\s@"']+(?:\.[^<>()\[\]\\.,;:\s@"']+)*)|".+")@(?:\[[0-9.]+\]|(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,})$'''
);
String? validateEmail(String? v) {
if (v == null || v.isEmpty) return 'Required';
return _emailRe.hasMatch(v) ? null : 'Not a valid e-mail';
}
...
TextFormField(validator: validateEmail)
The email_validator Package
A popular alternative is to use the `email_validator` package. This method relies on a purpose-built parser instead of a single regular expression. The package is unit-tested against thousands of cases and covers various formats like dot-atom, quoted strings, and address literals.
After you add the package as a dependency, you can import it and call the static `EmailValidator.validate` method. This method returns a boolean that indicates whether the input string conforms to the correct email syntax. It provides the same results on all platforms.
import 'package:email_validator/email_validator.dart';
...
if (EmailValidator.validate(input)) { … }
A Composable Validator Layer
This method applies the Strategy design pattern to create a flexible validation pipeline. You can use a package like `flutter_easy_validator` or build your own implementation. It allows you to chain multiple independent validation rules together for a single field.
The code shows how to compose a validator that checks for several conditions in sequence. It first confirms the field is not empty, then checks for valid email format, and finally applies a custom rule. This modular approach makes unit tests trivial and simplifies rule management.
TextFormField(validator: validator);
final validator = EasyValidator.compose([
EasyValidator.required(),
EasyValidator.email(), // built-in strategy
EasyValidator.notStartWith('test')// add your own rule
]).validate;
TextFormField(validator: validator);
Challenges of Email Validation in Flutter
Client-side validation techniques check syntax but overlook deeper issues. These approaches introduce problems with maintainability, future-proofing, and the overall user experience.
- A simple inline regular expression cannot fully parse RFC 5322 standards. It often rejects valid addresses with quoted strings or comments and accepts invalid ones. This makes the pattern difficult to maintain.
- Static client-side methods fail to account for new gTLDs and international domain names. An inline regex or a package with a fixed TLD list quickly becomes outdated and rejects valid, modern email addresses.
- Client-side validation only confirms syntax, not deliverability. Methods like
email_validator
cannot check for MX records or disposable domains. Synchronous checks on the UI thread cannot perform network calls without application jank. - A complex inline regular expression can cause performance issues. Certain inputs may trigger catastrophic backtracking in Dart's regex engine, which freezes the user interface and degrades the user experience.
Validate Emails with Abstract API
Add email validation to your Flutter app to ensure data accuracy and a better user experience.
Get started for free
How Abstract API Handles Email Validation in Flutter
Abstract API addresses the core weaknesses of traditional methods. It moves the validation logic from client-side checks to a network service that returns a full deliverability report.
- Performs real-time MX and SMTP probes to confirm server and mailbox existence.
- Filters disposable and role-based email addresses.
- Offers typo autocorrection for common mistakes.
- Provides a machine-learning-driven quality score.
- Returns a unified deliverability flag for a clear result.
How to Add Abstract API to Your Dev Environment
Once you know Abstract’s capabilities, the addition of its email validation API to your project is simple.
- Sign up at Abstract API, enable the Email Verification & Validation API, and copy your api_key.
- In your pubspec.yaml file, add the http package: http: ^1.2.0. Then, run flutter pub get.
- Create a new file at lib/services/email_validator_service.dart. Import ‘dart:convert’ and ‘package:http/http.dart’ as http.
- Construct a Uri with the host emailvalidation.abstractapi.com, the path /v1/, and query parameters for your api_key and the user's email.
- Issue an http.get(uri) request. You should throw an exception if the statusCode is not 200. Then, parse the response with jsonDecode(body).
- Expose the parsed object to your form-level validator. You can block or warn users based on the deliverability or quality_score thresholds you define.
Sample Email Validation Implementation with Abstract API
The Dart function below sends a user's email address to the Abstract API endpoint. The API processes the address and returns a detailed JSON object. This response contains a clear deliverability status, a quality score, and several boolean flags that check for disposable domains, role-based accounts, and more.
Future<EmailReport> validateEmail(String email) async {
final uri = Uri.https('emailvalidation.abstractapi.com', '/v1/', {
'api_key': 'YOUR_API_KEY',
'email' : email,
});
final res = await http.get(uri);
if (res.statusCode != 200) throw Exception('API error');
return EmailReport.fromJson(jsonDecode(res.body));
}
Here is a sample response for a valid email address:
{
"email": "johnsmith@gmail.com",
"autocorrect": "",
"deliverability": "DELIVERABLE",
"quality_score": 0.9,
"is_valid_format": { "value": true, "text": "TRUE" },
"is_free_email": { "value": true, "text": "TRUE" },
"is_disposable_email": { "value": false, "text": "FALSE" },
"is_role_email": { "value": false, "text": "FALSE" },
"is_catchall_email": { "value": false, "text": "FALSE" },
"is_mx_found": { "value": true, "text": "TRUE" },
"is_smtp_valid": { "value": true, "text": "TRUE" }
}
In this example, the DELIVERABLE status, along with true flags for is_mx_found and is_smtp_valid, confirms the mailbox can receive mail. The high quality_score of 0.9 suggests confidence. All risk flags are false, so the address is safe to use immediately.
Final Thoughts
Traditional validation methods often fail because they only check syntax. They cannot detect disposable addresses, typos, or invalid mail servers, which leaves your app open to bad data.
Abstract API solves these problems with a comprehensive, real-time check that confirms actual deliverability. Consider an account on Abstract API to get your free API key.
Validate Emails with Abstract API
Implement email validation in your Flutter app to improve data quality and prevent fake signups.
Get started for free