Home > Enterprise >  How to use email_validator to validate an email address
How to use email_validator to validate an email address

Time:12-10

I'm trying to build a sign up page for my application. I tried to check if the email is valid or not by using email_validator 2.0.1, but it doesn't work, it doesn't give any error nor does it print the error text.

My code is below:

Widget buildSignInForm() {
    final _signInFormKey = GlobalKey<FormState>();
    TextEditingController _emailController = TextEditingController();
    TextEditingController _passwordController = TextEditingController();
    return Padding(
      padding: const EdgeInsets.all(20.0),
      child: Form(
        key: _signInFormKey,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              "Lütfen Giriş Yapınız",
              style: TextStyle(fontSize: 25),
            ),
            SizedBox(
              height: 20,
            ),
            TextFormField(
              controller: _emailController,
              validator: (value) {
                if (value != null && !EmailValidator.validate(value)) {
                  return "Please Enter a Valid E-mail";
                } else {
                  return null;
                }
              },

CodePudding user response:

I'm using form_field_validator

form_field_validator

import 'package:flutter/material.dart';
import 'package:form_field_validator/form_field_validator.dart';
void main() {
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    home: FormValidationExample(),
  ));
}

class FormValidationExample extends StatelessWidget with InputValidationMixin {
  final formGlobalKey = GlobalKey < FormState > ();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Form validation example'),
      ),
      body:
      Padding(
        padding: const EdgeInsets.symmetric(horizontal: 24),
          child: Form(
            key: formGlobalKey,
            child: Column(
              children: [
            const SizedBox(height: 50),
                  TextFormField(
                    decoration: InputDecoration(
                      labelText: "Email"
                    ),
                    validator: (email) {
                      if (isEmailValid(email)) return null;
                      else
                        return 'Enter a valid email address';
                    },
                  ),
                  const SizedBox(height: 24),
                    TextFormField(
                      decoration: InputDecoration(
                        labelText: "Password",
                      ),
                      maxLength: 6,
                      obscureText: true,
                      validator: (password) {
                        if (isPasswordValid(password)) return null;
                        else
                          return 'Enter a valid password';
                      },
                    ),
                    const SizedBox(height: 50),
                      ElevatedButton(
                        onPressed: () {
                          if (formGlobalKey.currentState.validate()) {
                            formGlobalKey.currentState.save();
                            // use the email provided here
                          }
                        },
                        child: Text("Submit"))
          ],
            ),
          ),
      ));
  }
}

mixin InputValidationMixin {
  bool isPasswordValid(String password) => password.length == 6;

  bool isEmailValid(String email) {
    Pattern pattern =
      r '^(([^<>()[\]\\.,;:\s@"] (\.[^<>()[\]\\.,;:\s@"] )*)|(". "))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9] \.) [a-zA-Z]{2,}))$';
    RegExp regex = new RegExp(pattern);
    return regex.hasMatch(email);
  }
}

enter image description here

CodePudding user response:

Try this code!

TextFormField(
 controller: _emailController,
 autovalidateMode: AutovalidateMode.onUserInteraction,
 validator: (value) {
            if (value.isEmpty) {
                return 'Enter your Email address';
             }
            if (!RegExp(r'^(([^<>()[\]\\.,;:\s@\"] (\.[^<>()[\]\\.,;:\s@\"] )*)|(\". \"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9] \.) [a-zA-Z]{2,}))$').hasMatch(value)) {
                return 'Enter a Valid Email address';
              }
               return null;
               },)

and then on Sign Up button or Register Button

if (formGlobalKey.currentState.validate()) {
   // take action what you want
  }

CodePudding user response:

Please refer below code

Solution 1

enter image description here enter image description here

class MainScreen extends StatefulWidget {
  MainScreen({Key key}) : super(key: key);

  @override
  _MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  final TextEditingController emailController = TextEditingController();

  final FocusNode emailFocus = FocusNode();

  final TextEditingController pswdController = TextEditingController();

  final FocusNode pswdFocus = FocusNode();

  final _validationKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  int validateEmail(String emailAddress) {
    String patttern = r'^[\w-\.] @([\w-] \.) [\w-]{2,4}$';
    RegExp regExp = new RegExp(patttern);
    if (emailAddress.isEmpty || emailAddress.length == 0) {
      return 1;
    } else if (!regExp.hasMatch(emailAddress)) {
      return 2;
    } else {
      return 0;
    }
  }

  int validatePassword(String pswd) {
    if (pswd.isEmpty || pswd.length == 0) {
      return 1;
    } else if (pswd != null && pswd.isNotEmpty && pswd.length <= 8) {
      return 2;
    } else {
      return 0;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.lightBlue,
        automaticallyImplyLeading: true,
        leading: Icon(
          Icons.arrow_back,
        ),
        title: Text("Example"),
        centerTitle: true,
      ),
      body: Container(
        padding: EdgeInsets.all(15.0),
        child: Column(
          children: [
            Form(
              key: _validationKey,
              child: Column(
                children: [
                  /* Email */
                  TextFormField(
                    autovalidateMode: AutovalidateMode.onUserInteraction,
                    /* autovalidate is disabled */
                    controller: emailController,
                    keyboardType: TextInputType.emailAddress,
                    onChanged: (val) {},
                    maxLines: 1,
                    validator: (value) {
                      int res = validateEmail(value);
                      if (res == 1) {
                        return "Please  fill email address";
                      } else if (res == 2) {
                        return "Please enter valid email address";
                      } else {
                        return null;
                      }
                    },
                    focusNode: emailFocus,
                    autofocus: false,
                    decoration: InputDecoration(
                      errorMaxLines: 3,
                      counterText: "",
                      filled: true,
                      fillColor: Colors.white,
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      disabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                        ),
                      ),
                      errorBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(4)),
                          borderSide: BorderSide(
                            width: 1,
                            color: Colors.red,
                          )),
                      focusedErrorBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Colors.red,
                        ),
                      ),
                      hintText: "Enter email address" ?? "",
                    ),
                  ),
                  SizedBox(
                    height: 15.0,
                  ),

                  /* Password */
                  TextFormField(
                    autovalidateMode: AutovalidateMode.onUserInteraction,
                    /* autovalidate is disabled */
                    controller: pswdController,
                    inputFormatters: [
                      FilteringTextInputFormatter.deny(RegExp(r"\s\s")),
                      FilteringTextInputFormatter.deny(RegExp(
                          r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])')),
                    ],
                    keyboardType: TextInputType.text,
                    maxLength: 160,
                    onChanged: (val) {},
                    obscureText: true,
                    maxLines: 1,
                    validator: (value) {
                      int res = validatePassword(value);
                      if (res == 1) {
                        return "Please enter password";
                      } else if (res == 2) {
                        return "Please enter minimum 9 characters";
                      } else {
                        return null;
                      }
                    },
                    focusNode: pswdFocus,
                    autofocus: false,
                    decoration: InputDecoration(
                      errorMaxLines: 3,
                      counterText: "",
                      filled: true,
                      fillColor: Colors.white,
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      disabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                        ),
                      ),
                      errorBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(4)),
                          borderSide: BorderSide(
                            width: 1,
                            color: Colors.red,
                          )),
                      focusedErrorBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Colors.red,
                        ),
                      ),
                      hintText: "Enter password" ?? "",
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(
              height: 15.0,
            ),
            OutlinedButton(
              onPressed: () {
                _validationKey.currentState.validate();
                if (emailController.text.isEmpty) {
                  emailFocus.requestFocus();
                } else if (pswdController.text.isEmpty ||
                    pswdController.text.length <= 8) {
                  pswdFocus.requestFocus();
                }
              },
              child: Text("Validate"),
            )
          ],
        ),
      ),
    );
  }
}


Solution 2

enter image description here

class HomeScreen extends StatelessWidget {
  HomeScreen({Key key}) : super(key: key);

  
  final _validationKey = GlobalKey<FormState>();

  final TextEditingController emailAddressTextController =
      TextEditingController();
  bool isValidEmail = true;

  bool isEmail(String string) {
    // Null or empty string is invalid
    if (string == null || string.isEmpty) {
      return false;
    }

    const pattern = r'^[\w-\.] @([\w-] \.) [\w-]{2,4}$';
    final regExp = RegExp(pattern);

    if (!regExp.hasMatch(string)) {
      return false;
    }
    return true;
  }

  int validateEmailAddress(String emailAddress) {
    String patttern = r'^[\w-\.] @([\w-] \.) [\w-]{2,4}$';
    RegExp regExp = new RegExp(patttern);
    if (emailAddress.isEmpty || emailAddress.length == 0) {
      return 1;
    } else if ((regExp.hasMatch(patttern))) {
      return 2;
    } else {
      return 0;
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.lightBlue,
        automaticallyImplyLeading: true,
        leading: Icon(
          Icons.arrow_back,
        ),
        title: Text("Example"),
        centerTitle: true,
      ),
      body: Container(
        padding: EdgeInsets.all(15.0),
        child: Column(
          children: [
            Form(
              key: _validationKey,
              child: Column(
                children: [
                  TextFormField(
                    autovalidateMode: AutovalidateMode.always,
                    /* autovalidate is set to true */
                    controller: emailAddressTextController,
                    inputFormatters: [
                      FilteringTextInputFormatter.deny(RegExp(r"\s\s")),
                      FilteringTextInputFormatter.deny(RegExp(
                          r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])')),
                    ],
                    keyboardType: TextInputType.emailAddress,
                    maxLength: 160,
                    onChanged: (val) {
                      isValidEmail = isEmail(val);
                    },
                    maxLines: 1,
                    validator: (value) {
                      if (!isValidEmail) {
                        return "Please enter valid email address";
                      } else if (value.isEmpty) {
                        return "please enter email address";
                      } else {
                        return null;
                      }
                      // int res = validateEmailAddress(value);
                      // if (res == 1) {
                      //   return "Please enter email address";
                      // } else if (res == 2) {
                      //   return "Please enter valid email address";
                      // } else {
                      //   return null;
                      // }
                    },
                    autofocus: false,
                    decoration: InputDecoration(
                      errorMaxLines: 3,
                      counterText: "",
                      filled: true,
                      fillColor: Colors.white,
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      disabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                        ),
                      ),
                      errorBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(4)),
                          borderSide: BorderSide(
                            width: 1,
                            color: Colors.red,
                          )),
                      focusedErrorBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Colors.red,
                        ),
                      ),
                      hintText: "Email Address" ?? "",
                    ),
                  ),

                 
                ],
              ),
            ),
            SizedBox(
              height: 15.0,
            ),
          ],
        ),
      ),
    );
  }
}


CodePudding user response:

The fastest and easiest solution is to use a regex expression:

extension EmailValidator on String {
  bool isValidEmail() {
    return RegExp(
            r'^(([^<>()[\]\\.,;:\s@\"] (\.[^<>()[\]\\.,;:\s@\"] )*)|(\". \"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9] \.) [a-zA-Z]{2,}))$')
        .hasMatch(this);
  }
}

And use extension of String for validate the email :

TextFormField(
  autovalidate: true,
  validator: (input) => input.isValidEmail() ? null : "Check your email",
)

Ref

  • Related