Ensuring user emails are valid is a key part of building a robust Flutter application. You'll find three common methods for email validation here, complete with code examples. We'll also break down the limitations of these approaches and show how Abstract API overcomes them.
How to Implement Email Validation in Flutter
Here are three common ways to validate user emails in your Flutter app. Each method includes a detailed explanation and a ready-to-use code snippet for your project.
Validation with an Inline Regular Expression
This approach keeps all validation logic on the client side. It employs a regular expression built from a well-known RFC 5322-style pattern. This pattern is defined in a 'RegExp' object and used inside a custom validator function.
The function, here named 'validateEmail', first checks if the input value is null or empty and returns a 'Required' message if so. Otherwise, it tests the input against the regular expression. It returns 'null' for a valid email or an error message for an invalid one. This function is then passed to a 'TextFormField' widget.
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)
Validation with the email_validator Package
For a more robust solution, you can use a dedicated package. The email_validator package contains a purpose-built parser rather than a single regular expression. It covers various formats like dot-atom, quoted strings, and address literals, and it is unit-tested against thousands of cases.
To use it, add 'email_validator:^3.0.0' to your project's dependencies. After you import the package, you can call the static 'EmailValidator.validate' method to check if an email address conforms to the proper syntax.
import 'package:email_validator/email_validator.dart';
...
if (EmailValidator.validate(input)) { … }
Validation with a Composable Layer
This method applies the Strategy design pattern to create a flexible validation layer. You can build your own or adopt a package like flutter_easy_validator. A field validates through a pipeline of independent rules, which allows for clear error messages and simple unit tests.
You can add or swap rules without a need to touch the call-site. This pattern is explored in detail in the article From Regex to Strategy. The example below composes a validator that checks if a field is required, is a valid email, and does not start with 'test'.
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 methods present several hidden complexities. These approaches often fall short of complete accuracy and can introduce performance issues that affect user experience and data quality.
- A simple inline regular expression cannot parse all valid formats like quoted strings or address literals. This abbreviated approach incorrectly rejects valid emails while it accepts invalid ones, and the pattern itself proves difficult to maintain.
- The internet constantly evolves with new domains and international characters. A static pattern, whether an inline regex or part of a package like email_validator, quickly becomes obsolete and silently rejects legitimate user addresses.
- Flutter’s synchronous validators cannot perform network checks for MX records or disposable domains without a risk of UI freezes. This limitation means client-side methods only confirm syntax, not if an email address actually exists.
- Complex regular expressions can trigger catastrophic backtracking on certain inputs, which freezes the application's UI. Even simple validation errors from these methods can distort widget layouts, which creates a poor 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 with a network endpoint that performs comprehensive validation and returns a full deliverability report.
- It performs real-time MX and SMTP probes to confirm a server accepts mail.
- It filters disposable and role-based email addresses.
- It suggests corrections for common typos in email addresses.
- It provides a machine-learning-driven quality score for each address.
- It returns a single, unified flag to indicate deliverability status.
How to Bring Abstract API to Your Dev Environment
Once you know Abstract’s capabilities, you can add its email validation API to your project with ease. Here are the steps to prepare your development environment.
- Sign up at AbstractAPI.com, enable the Email Verification & Validation API, and copy the generated api_key.
- In your pubspec.yaml file, add http: ^1.2.0 (or the latest version) and then execute flutter pub get.
- Create a file at lib/services/email_validator_service.dart and 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 email.
- Issue an http.get request with the Uri. If the status code is not 200, throw an exception, otherwise, parse the response body with jsonDecode.
- Expose the parsed object to your form-level validator. Block or warn users based on the deliverability or quality_score thresholds you define.
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));
}
Sample Email Validation Implementation with Abstract API
The Dart code above sends a GET request to the API endpoint with the user's email. In return, Abstract API provides a detailed JSON response that contains a full deliverability report. Below 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" }
}
This response offers a clear picture of the email's validity. A "DELIVERABLE" status, with "true" values for is_mx_found and is_smtp_valid, confirms the mailbox accepts mail. The quality_score of 0.9 indicates high confidence. While is_free_email is "true", all risk flags like disposable, role, and catch-all are "false", so the address is safe to use.
Final Thoughts
Traditional validation methods often fail because they only check syntax. They miss critical issues like disposable addresses, typos, and invalid mail servers. Abstract API overcomes these limitations with a comprehensive check that confirms actual deliverability.
To reliably validate user emails, 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