Beginner
Form Validation and TextFormField in Flutter
· 7 min read
Form and GlobalKey<FormState>
A Form widget groups several TextFormFields together and lets you validate all of them at once through a formKey. Each field keeps running its own validator, but the form gives you one place to trigger and check them all.
final _formKey = GlobalKey<FormState>();
Form(
key: _formKey,
child: Column(
children: [
TextFormField(
decoration: const InputDecoration(labelText: 'Email'),
validator: _validateEmail,
),
TextFormField(
decoration: const InputDecoration(labelText: 'Password'),
obscureText: true,
validator: _validatePassword,
),
],
),
)The validator Function
Every TextFormField takes a validator: it receives the current text and returns either null (the field is valid) or a String that's shown as the error message right under the field. Keep each validator focused on one field — combine multiple checks inside it rather than spreading the logic across the widget tree.
String? _validateEmail(String? value) {
if (value == null || value.isEmpty) {
return 'Email cannot be empty';
}
final emailRegex = RegExp(r'^[^@\s]+@[^@\s]+\.[^@\s]+