'How to validate email in a TextFormField

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.



Solution 1:[1]

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;
  }

Solution 2:[2]

  TextFormField(
          validator: (val) => val.isEmpty || !val.contains("@")
              ? "enter a valid eamil"
              : null,
         
          decoration: InputDecoration(hintText: 'email'),
        ),

In the validator first we are checking if the formfeild is empty and also we are checking if the text entered dose not contains "@" in it . If those conditions are true then we are returning a text "enter a valid email" or else we are not returning anything

Solution 3:[3]

I suggest use of this excellent library called validators

  1. Add dependency to your package's pubspec.yaml file:
    dependencies:
      validators: ^2.0.0 # change to latest version
  1. Run from the command line:
    $ pub get
    // on VSCode u need not do anything.
  1. Import in your Dart code:
    import 'package:validators/validators.dart';
  1. Validate your field
Form(
  child: TextFormField(
    validator: (val) => !isEmail(val) ? "Invalid Email" : null;,
  ),
)

Solution 4:[4]

The previous answers all discuss options for verifying a TextFormField in a Form. The question asks about doing this in

TextFormField or TextField

TextField does not support the validator: named parameter but you can use any of the previously mentioned techniques to check the validity of the email every time the user modifies the email address text. Here is a simple example:

  TextField(
    keyboardType: TextInputType.emailAddress,
    textAlign: TextAlign.center,
    onChanged: (value) {
      setState(() {
        _email = value;
        _emailOk = EmailValidator.validate(_email);
      });
    },
    decoration:
        kTextFieldDecoration.copyWith(hintText: 'Enter your email'),
  ),

You can use the validation result as you see fit. One possibility is to keep a login button deactivated until a valid email address has been entered:

  ElevatedButton(
    child: Text('Log In'),
    // button is disabled until something has been entered in both fields.
    onPressed: (_passwordOk && _emailOk) ? ()=> _logInPressed() : null,
  ),

Solution 5:[5]

No need to use external libraries or Regex! Put your text field inside a form, set autovalidate to 'always' and inside TextFormField add a validator function:

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

Validator function:

 String? validateEmail(String? value) {    
      if (value != null) {
        if (value.length > 5 && value.contains('@') && value.endsWith('.com')) {
          return null;
        }
     return 'Enter a Valid Email Address';
    }

note: length > 5 because '.com' and '@' make 5 characters.

Solution 6:[6]

QUICK FIX ? Use this in your TextFormField.

validator: (value) {
  if(value == null || value.isEmpty || !value.contains('@') || !value.contains('.')){
    return 'Invalid Email';
  }
  return null;
},

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joaquin Iurchuk
Solution 2
Solution 3 raaaay
Solution 4 j-vasil
Solution 5 Adrish
Solution 6 Tushar Khatri