Skip to main content

Flutter TextField Email Form Validation - RegEx

Email is part of every digital information exchange system. In today's digital world before accessing any service platform based digitally online we will need Email. Sometimes user by mistake enters wrong formatted email. So when we create a mobile or web based application than email format should be correct. In today's tutorial we will set email form validation on TextFormField with RegEx.

Flutter TextField Email Form Validation - RegEx

1. Creating a Form State type Global key to save, reset and validate every text field present in Form.
final formGlobalKey = GlobalKey<FormState>();
2. Creating a Boolean variable with default False value assigned. We will use this Boolean value as final form submission validator.
  bool isValid = false;
3. Creating a function submit. In this function we would update the isValid variable with State to store final output on submit button.
  void submit() {
    setState(() {
      // Check Email is Vailid and save True.
      isValid = formGlobalKey.currentState!.validate();
    });
  }
4. Creating Form widget. In the form widget we will define Global Key and put Text form field with email validation with Regex.
Form(
        key: formGlobalKey,
        child: Container(
            margin: const EdgeInsets.all(18),
            child:
                Column(mainAxisAlignment: MainAxisAlignment.center, children: [
              TextFormField(
                decoration: const InputDecoration(
                    labelText: 'Type email Here...',
                    border: OutlineInputBorder()),
                keyboardType: TextInputType.emailAddress,
                validator: (value) {
                  // Check & Show Message if TextFormField is Empty.
                  if (value == null || value.isEmpty) {
                    return 'Email field is required.';
                  }
                  // Check & Show Message if TextFormField Email is Valid.
                  if (!RegExp(r'\S+@\S+\.\S+').hasMatch(value)) {
                    return "Please enter valid email.";
                  }
                  // Returns NULL on Valid Email.
                  return null;
                },
              ),
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.teal,
                  //textStyle: const TextStyle(fontSize: 21),
                ),
                onPressed: submit,
                child: const Text('Verify Email'),
              ),
              isValid
                  ? const Text(
                      'Email is Correct...',
                      style: TextStyle(color: Colors.red),
                    )
                  : const SizedBox()
            ])));
Screenshots:
Flutter TextField Email Validation
Flutter TextField Email Form Validation - RegEx
Flutter Show message on wrong email enter

Source code for main.dart file:
import 'package:flutter/material.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(home: Scaffold(body: MyApp()));
  }
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

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

class MyAppState extends State {
  final formGlobalKey = GlobalKey<FormState>();
  bool isValid = false;

  void submit() {
    setState(() {
      // Check Email is Vailid and save True.
      isValid = formGlobalKey.currentState!.validate();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Form(
        key: formGlobalKey,
        child: Container(
            margin: const EdgeInsets.all(18),
            child:
                Column(mainAxisAlignment: MainAxisAlignment.center, children: [
              TextFormField(
                decoration: const InputDecoration(
                    labelText: 'Type email Here...',
                    border: OutlineInputBorder()),
                keyboardType: TextInputType.emailAddress,
                validator: (value) {
                  // Check Show Message if TextFormField is Empty.
                  if (value == null || value.isEmpty) {
                    return 'Email field is required.';
                  }
                  // Check Show Message if TextFormField Email is Valid.
                  if (!RegExp(r'\S+@\S+\.\S+').hasMatch(value)) {
                    return "Please enter valid email.";
                  }
                  // Returns NULL on Valid Email.
                  return null;
                },
              ),
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.teal,
                  //textStyle: const TextStyle(fontSize: 21),
                ),
                onPressed: submit,
                child: const Text('Verify Email'),
              ),
              isValid
                  ? const Text(
                      'Email is Correct...',
                      style: TextStyle(color: Colors.red),
                    )
                  : const SizedBox()
            ])));
  }
}

Comments