Email Validation In the Flutter

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 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 = "";
      });
    }
  }
}

Output:

For more information please click on here

Thanks for reading … 🙂

Leave a Comment