Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate email in a TextFormField

Tags:

flutter

There is a way to validate the input of the user with a TextFormField or TextField,to reject the input if it's not an email.

like image 630
Andres Diaz Avatar asked Aug 06 '20 22:08

Andres Diaz


People also ask

How do I validate email in Flutter?

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.

How do I validate HTML email?

The <input type="email"> defines a field for an e-mail address. The input value is automatically validated to ensure it is a properly formatted e-mail address. To define an e-mail field that allows multiple e-mail addresses, add the "multiple" attribute.

What are two ways to validate an email address?

There are many free tools that also validate email addresses; ValidateEmailAddress, EmailValidator and Pabbly Email Verification are few of such examples. First, you need to bulk upload your list of email IDs.


Video Answer


2 Answers

You can use regex for this

Form and TextFormField like so

Form(
  autovalidateMode: AutovalidateMode.always,
  child: TextFormField(
    validator: (value) => validateEmail(value),
  ),
)

then the validation function

String validateEmail(String? value) {
    String pattern =
        r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]"
        r"{0,253}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]"
        r"{0,253}[a-zA-Z0-9])?)*$";
    RegExp regex = RegExp(pattern);
    if (value == null || value.isEmpty || !regex.hasMatch(value))
      return 'Enter a valid email address';
    else
      return null;
  }
like image 64
JideGuru Avatar answered Nov 09 '22 03:11

JideGuru


To validate the form, you can use the autovalidate flag and set up a validator for email. There are many options, including regex or manually writing your own checker, but there are also packages available which implement email checking already.

For example, https://pub.dev/packages/email_validator.

To use it, add it to your pubspec:

dependencies:
  email_validator: '^1.0.0'
import 'package:email_validator/email_validator.dart';

...

Form(
  autovalidate: true,
  child: TextFormField(
    validator: (value) => EmailValidator.validate(value) ? null : "Please enter a valid email",
  ),
)

There are many other validation packages, some of which support may different types of validation. See this search for more https://pub.dev/packages?q=email+validation.

like image 33
rmtmckenzie Avatar answered Nov 09 '22 05:11

rmtmckenzie