Text field validation in flutter
The most crucial thing to accomplish before submitting the text written by the user and informing them of an error message if mistakenly filled by the user is to verify the input.
Textfield Name Validation
We will validate if the user has entered a valid name by checking the length of the name entered by the user.
final _formKey = GlobalKey<FormState>();
final TextEditingController _nameController = new TextEditingController();
Form(
key: _formKey,
child:Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 5,bottom: 5),
child: Card(elevation: 3,
child: TextFormField(
controller: _nameController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: ‘Enter Name’,
),
keyboardType: TextInputType.text,
validator: validateName,
),
),
)
]
)
)
String? validateName(String? value) {
if (value!.length < 3)
return ‘Name must be more than 2 charater’;
else
return null;
}
void _submit() {
if (_formKey.currentState!.validate()) {
// TODO SAVE DATA
}
}
Textfield Phone Validation
We can check if the user has entered valid digits while entering the phone number.
final _formKey = GlobalKey<FormState>();
final TextEditingController _phoneNumberController = new TextEditingController();
Form(
key: _formKey,
child:Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 5,bottom: 5),
child: Card(elevation: 3,
child: TextFormField(
controller: _nameController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: ‘Enter Phone Number’,
),
keyboardType: TextInputType.phone,
validator: validateMobile,
),
),
)
]
)
)
String? validateMobile(String? value) {
// Indian Mobile number are of 10 digit only
if (value!.length != 10)
return ‘Mobile Number must be of 10 digit’;
else
return null;
}
void _submit() {
if (_formKey.currentState!.validate()) {
// TODO SAVE DATA
}
}
Textfield Email Validation
For checking email validation in flutter we will use the regex expression string.
final _formKey = GlobalKey<FormState>();
final TextEditingController _emailController = new TextEditingController();
Form(
key: _formKey,
child:Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 5,bottom: 5),
child: Card(elevation: 3,
child: TextFormField(
controller: _emailController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: ‘Enter Email Address’,
),
keyboardType: TextInputType.emailAddress,
validator: validateEmail,
),
),
),
]
)
)
String? validateEmail(String? value) {
String pattern =
r’^(([^<>()[\]\\.,;:\s@\”]+(\.[^<>()[\]\\.,;:\s@\”]+)*)|(\”.+\”))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$’;
RegExp regex = RegExp(pattern);
if (!regex.hasMatch(value!))
return ‘Enter Valid Email’;
else
return null;
}
void _submit() {
if (_formKey.currentState!.validate()) {
// TODO SAVE DATA
}
}
For Validating Textfield we will use two validating method
Flutter Form Widget
Textfield Widget
import ‘package:flutter/material.dart’;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: ‘Flutter Demo’,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: ‘Flutter Demo Home Page’),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _formKey = GlobalKey<FormState>();
final TextEditingController _nameController = new TextEditingController();
final TextEditingController _phoneNumberController = new TextEditingController();
final TextEditingController _emailController = new TextEditingController();
void _submit() {
if (_formKey.currentState!.validate()) {
// TODO SAVE DATA
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Form(
key: _formKey,
child: ListView(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 5,bottom: 5),
child: Card(elevation: 3,
child: TextFormField(
controller: _nameController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: ‘Enter Name’,
),
keyboardType: TextInputType.text,
validator: validateName,
),
),
),
Padding(
padding: const EdgeInsets.only(top: 5,bottom: 5),
child: Card(elevation: 3,
child: TextFormField(
controller: _phoneNumberController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: ‘Enter Phone Number’,
),
keyboardType: TextInputType.phone,
validator: validateMobile,
),
),
),
Padding(
padding: const EdgeInsets.only(top: 5,bottom: 5),
child: Card(elevation: 3,
child: TextFormField(
controller: _emailController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: ‘Enter Email Address’,
),
keyboardType: TextInputType.emailAddress,
validator: validateEmail,
),
),
),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _submit,
tooltip: ‘Submit’,
child: const Icon(Icons.check),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
String? validateEmail(String? value) {
String pattern =
r’^(([^<>()[\]\\.,;:\s@\”]+(\.[^<>()[\]\\.,;:\s@\”]+)*)|(\”.+\”))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$’;
RegExp regex = RegExp(pattern);
if (!regex.hasMatch(value!))
return ‘Enter Valid Email’;
else
return null;
}
String? validateMobile(String? value) {
// Indian Mobile number are of 10 digit only
if (value!.length != 10)
return ‘Mobile Number must be of 10 digit’;
else
return null;
}
String? validateName(String? value) {
if (value!.length < 3)
return ‘Name must be more than 2 charater’;
else
return null;
}
}