Email Validation In the Flutter
Limited Time Offer!
For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!
Before sending the userās input to the server, email validation is the best practice. We should check the email address to see if it is valid or not and display it to the user. For verifying the email address, we can use a regEx pattern, which is a little more complex to construct.
Instead of using the regEx pattern, we can use the coolest package inĀ the pub.devĀ calledĀ email_validatorĀ to achieve the same result. In this article, we are going to look at theĀ email_validatorĀ package.
About email_validator:
As previously mentioned, this is a simple Dart class for validating email addresses without the use of RegEx.
Adding Dependecy:
To use this package, we should first add it to the pubspec.yaml file and then run pug get.
dependencies:
flutter:
sdk: flutter
email_validator: ^2.0.1
Import Package:
We can use it in our Dart code after installing the package.
import 'package:email_validator/email_validator.dart';
Validating the Email Address with email_validator :
The static methodĀ validate()Ā in theĀ EmailValidatorĀ class will be used to validate the email address. It returns a bool value; if the email address is valid, the returned value is true; otherwise, the returned value is false.
static bool validate(String email,
[bool allowTopLevelDomains = false, bool allowInternational = true])
If we look at the above code, we can see that the validate(ā¦) method has three parameters. Out of the three, we should pass the email address as sting, and the other two are optional.
allowTopLevelDomains:Ā If [allowTopLevelDomains] is set to ātrue,ā the validator will accept addresses with top-level domains such as āemail@example.com.ā The default value is āfalseā.
allowInternational:Ā If [allowInternational] is set to ātrue,ā the validator will validate the email address using the newer International Email standards. The default value is ātrueā.
const String email = 'fredrik.eilertsen@gail.com';
final bool isValid = EmailValidator.validate(email);
print('Email is valid? ' + (isValid ? 'yes' : 'no'));
Simply pass the email address as a string toĀ validate(..), which returns a Boolean value. We can update the Ui based on that value. The code above shows a simple example of how to use theĀ validate(..)Ā method.
Implementation of Email validation on the login page
On the login page, there are two text fields: one for email address and one for password. Using the EmailValidator, we added email verification to the email field.
Create a newĀ Flutter project, replace the code below, and run the application. Weāll come to know more about the concept.
import 'package:flutter/material.dart';
import 'package:email_validator/email_validator.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: LogInPage(),
);
}
}
class LogInPage extends StatefulWidget {
@override
_LogInPageState createState() => _LogInPageState();
}
class _LogInPageState extends State<LogInPage> {
String _errorMessage = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Email validation'),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(labelText: 'Email'),
onChanged: (val){
validateEmail(val);
},
),
TextFormField(
keyboardType: TextInputType.visiblePassword,
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () {
print("Sing in Clicked");
},
child: Text('Sign in'),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(_errorMessage, style: TextStyle(color: Colors.red),),
),
],
),
),
);
}
void validateEmail(String val) {
if(val.isEmpty){
setState(() {
_errorMessage = "Email can not be empty";
});
}else if(!EmailValidator.validate(val, true)){
setState(() {
_errorMessage = "Invalid Email Address";
});
}else{
setState(() {
_errorMessage = "";
});
}
}
}
For more information please click onĀ here