-1.4 C
New York
Wednesday, November 29, 2023

How to validate email in Flutter without plugins

This article shows you an elegant method to validate email in Flutter. We’ll use the RegExp class of dart:core for working with regular expression.

The email pattern:Advertisements


The Code

Create a new Flutter project and replace the default code in main.dart with the following:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  Widget build(BuildContext context) {
    return MaterialApp(
      // Hide the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      theme: ThemeData.light(),
      home: const HomePage(),

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  _HomePageState createState() => _HomePageState();

class _HomePageState extends State<HomePage> {
  final _form = GlobalKey<FormState>();
  bool _isValid = false;

  void _saveForm() {
    setState(() {
      _isValid = _form.currentState!.validate();

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Kindacode.com'),
      body: Padding(
        padding: const EdgeInsets.all(25),
        // the Form here
        child: Form(
          key: _form,
          child: Column(
            children: [
                    const InputDecoration(labelText: 'Enter your email'),
                keyboardType: TextInputType.emailAddress,
                validator: (value) {
                  // Check if this field is empty
                  if (value == null || value.isEmpty) {
                    return 'This field is required';

                  // using regular expression
                  if (!RegExp(r'S+@S+.S+').hasMatch(value)) {
                    return "Please enter a valid email address";

                  // the email is valid
                  return null;
              const SizedBox(height: 25),
                  onPressed: _saveForm, child: const Text('Check Email')),
              const SizedBox(height: 25),
              _isValid ? const Text('Your email seems nice!') : Container()

Try it:

Hope this helps. Further reading:


You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.


Related Articles

Latest Articles