In this article, we’ll learn about the Flutter textformfield validator email in detail. This article will focus on teaching how we can use the validator of textformfield and to make things more interesting, we’ll validate an email that the user enters and we’ll check whether it’s valid or not. So let’s jump right into it.
What is Flutter Textformfield Validator?
It’s a parameter of the textformfield widget class and it’s a callback function. The role of this function is to validate whether the data entered by the user is valid or not when the user submits the form. We can logically create some conditions for the data so if it meets those conditions then the data is valid, else it’ll be invalid.
Implementing Email Validation using Textformfield Validator (Code Example)
Step 1: Create a simple Email Field and a Submit Button
First, we’ll create an email textformfield widget that will take input from the user. Also, we’ll create an elevated button that will check if the form(one textformfield in this case) is validated or not and perform operations based on the result. See below code:
TextFormField( decoration: InputDecoration(hintText: 'Enter Email Here') ),
ElevatedButton( onPressed: () { }, child: Text('Submit Here'), )
This is the basic code for the textformfield with a hint text and the elevated button.
Step 2: Global Key
final _formKey = GlobalKey<FormState>();
Form( key: _formKey, child: Column( children:[ // textformfield and button code here ]))
The global key’s role is to identify a widget uniquely in a widget tree. It can be accessed inside the widget tree from anywhere(inside the widget tree). It allows us to interact with the state of this form widget. Its role is to get the current state of the form after validating it. In this code, the column will have a textformfield and a button.
Step 3: Custom function of Email Validation
String? _validateEmail(String? value) { if (value == null || value.isEmpty) { return 'Email cannot be empty'; } String emailPattern = r'^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$'; RegExp regex = RegExp(emailPattern); if (!regex.hasMatch(value)) { return 'Email is invalid'; } return null; }
In this code, we created a function that will first check whether the email field is empty or not. If it’s empty then it’ll return a string ‘Email cannot be empty’. If it’s not empty then we are using a regular expression(RexExp) to validate the format of email. You can use some email validation packages to validate the email as well.
Step 4: Specify the validator and onSaved Parameter
String email = '';
TextFormField( validator: _validateEmail, onSaved: (String? value) { email = value!; }, )
Step 5: Elevated Button’s OnPressed Functionality
onPressed: () { if (_formKey.currentState!.validate()) { _formKey.currentState!.save(); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('Email is submitted successfully: $email'), ), ); } },
Step 6: Testing the Code
In this code, we tested the app by submitting an empty field, an invalid email format, and a valid email format as well and the output can be seen in the above images.
Flutter Textformfield Validator Email Source Code
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Email Validation'), centerTitle: true, ), body: Center( child: Padding( padding: EdgeInsets.all(21), child: SimpleForm(), ), ), ), ); } } class SimpleForm extends StatefulWidget { @override _SimpleFormState createState() => _SimpleFormState(); } class _SimpleFormState extends State<SimpleForm> { final _formKey = GlobalKey<FormState>(); String email = ''; String? _validateEmail(String? value) { if (value == null || value.isEmpty) { return 'Email cannot be empty'; } String emailPattern = r'^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$'; RegExp regex = RegExp(emailPattern); if (!regex.hasMatch(value)) { return 'Email is invalid'; } return null; } @override Widget build(BuildContext context) { return Form( key: _formKey, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextFormField( decoration: InputDecoration(hintText: 'Enter Email Here'), validator: _validateEmail, onSaved: (String? value) { email = value!; }, ), SizedBox(height: 40), ElevatedButton( onPressed: () { if (_formKey.currentState!.validate()) { _formKey.currentState!.save(); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('Email is submitted successfully: $email'), ), ); } }, child: Text('Submit Here'), ), ], ), ); } }
Conclusion
In conclusion, we now have a detailed practical understanding of how to implement Flutter textformfield validator email in our own code. Do ask if you still have any questions. Also, don’t forget to visit our other articles on other Flutter concepts like Flutter Firebase Crud, Firebase Auth, Flutter widgets, Dart programs, and much more.
Thank you for reading it.