Sub topic 8
Choosing When Validation Runs
Assume you know basic Dart, nullable types, closures, StatefulWidget, setState, and layouts such as Column and Scaffold. In Flutter, validation timing controls when a TextFormField calls its validator and displays an error.
A validator returns an error message when the value is invalid. It returns null when the value is valid. The AutovalidateMode setting decides when Flutter runs that function:
| Mode | Validation timing | Typical use |
|---|---|---|
| `disabled` | Only when code calls `validate()` | Validate on submit |
| `onUserInteraction` | After the user edits the field | Immediate feedback after the first edit |
| `always` | During every validation-triggering build | Special cases where errors must always be visible |
Manual validation on submit
The default mode is disabled. This keeps the form quiet while the user is entering data. When the user taps Submit, call validate() on the form's FormState.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: EmailPage()));
}
class EmailPage extends StatefulWidget {
const EmailPage({super.key});
@override
State<EmailPage> createState() => _EmailPageState();
}
class _EmailPageState extends State<EmailPage> {
final _formKey = GlobalKey<FormState>();
void _submit() {
final isValid = _formKey.currentState!.validate();
if (isValid) {
debugPrint('Form can be submitted');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(24),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(labelText: 'Email'),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Email is required';
}
if (!value.contains('@')) {
return 'Enter a valid email address';
}
return null;
},
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _submit,
child: const Text('Submit'),
),
],
),
),
),
);
}
}validate() returns true only when every field validator returns null. It also updates the form so that error messages become visible.
Validate after the user starts typing
AutovalidateMode.onUserInteraction avoids showing errors on the first screen build. After the user changes a field, Flutter validates it as the user interacts with it.
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(labelText: 'Username'),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Username is required';
}
return null;
},
)This mode usually gives the best balance for forms. The user receives feedback while fixing a value, but an untouched form does not immediately display a wall of errors.
Common timing mistakes
- Using
alwayswithout a clear reason can show errors before the user has had a chance to enter anything. - Calling
validate()insidebuild()can cause confusing rebuild behavior. Validate from an event such as a button press. - Checking only the current field can miss errors in other fields.
FormState.validate()checks the complete form. - Changing
autovalidateModedoes not replace server-side validation. A server can reject a value that is locally well-formed.
Exercise
Which mode should you choose when errors must stay hidden until the user submits the form?
Show answer
Use AutovalidateMode.disabled and call _formKey.currentState!.validate() in the submit handler.