Sub topic 8
Choosing when validation runs
This chapter covers AutovalidateMode, the setting that decides when a field shows its error. It assumes you know how to build a Form with a GlobalKey<FormState>, how a TextFormField takes a validator, and how setState works. A validator returns an error string or null. This chapter is about when Flutter calls that validator.
Why timing matters
A validator is a pure function from a value to a message. Flutter decides separately when to run it and when to show the result. That timing changes how the form feels to the user.
- If validation runs on the first frame, the user sees red errors on a form they have not touched.
- If it runs only on submit, the user learns about every mistake at once, and only after pressing the button.
- If it runs on every keystroke, the user sees "Enter a valid email" after typing a single letter.
The best choice is usually in between. Show errors after the user has interacted with a field, and keep them current as the user corrects them.
The three AutovalidateMode values
AutovalidateMode is an enum with three values. You can set it on a TextFormField, on a FormField, or on the Form itself.
| Value | When the validator runs | Typical use |
|---|---|---|
| `disabled` | Only when `validate()` is called, for example by `FormState.validate()` | Short forms where one summary of errors on submit is enough |
| `always` | On every build, including the first, before the user touches anything | Rare. Editing a record that is already filled in and may be invalid |
| `onUserInteraction` | After the user first changes the field, then on every later change | Most forms |
disabled is the default. With it, nothing is validated until your code asks for it. Calling FormState.validate() runs every validator in the form and draws the errors.
What counts as interaction
With onUserInteraction, a field is marked as interacted with when its value changes through user input. In practice that is typing, pasting or deleting. Before that moment the field stays quiet. After it, the validator runs after each change, and the error text updates as the user fixes the input.
Tapping into the field and leaving without typing does not count as a change. The field stays clean. Focus alone does not trigger validation.
Setting the mode on a field
The SignUpForm from the earlier chapter already uses this setting on its email field:
TextFormField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(labelText: 'Email'),
validator: _validateEmail,
)With this setting, a user who types ann sees "Enter a valid email address" immediately. When they type @, the message disappears. If they delete everything, "Email is required" appears.
The mode applies only to this field. Other fields in the form keep their own mode, so you can mix them. For example, you can validate a username as the user types but leave a long free-text field alone until submit.
Setting the mode on the Form
Form has its own autovalidateMode. A field uses its own setting if you provide one. Otherwise it follows the form's setting.
Form(
key: _formKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Column(
children: [
TextFormField(
decoration: const InputDecoration(labelText: 'Name'),
validator: requiredField('Name is required'),
),
TextFormField(
decoration: const InputDecoration(labelText: 'City'),
validator: requiredField('City is required'),
),
],
),
)This sets the policy once. Both fields validate after the user changes them. The requiredField helper comes from the reusable validators in the Topic Spine:
typedef Validator = String? Function(String? value);
Validator requiredField(String message) =>
(value) => (value == null || value.trim().isEmpty) ? message : null;A subtle point about Form-level interaction: when any field in the form changes, the form notifies its fields. In practice, with onUserInteraction set on the form, a change in one field can cause the other fields to re-run their validators if those fields have already been interacted with. Fields the user has not touched stay quiet.
Submit-first, then live
A common pattern is to stay quiet until the first submit, and then switch to live validation. The user sees no errors while filling in the form. After a failed submit, errors update as they fix each field.
Hold the mode in state and change it when validation fails:
import 'package:flutter/material.dart';
class LoginForm extends StatefulWidget {
const LoginForm({super.key});
@override
State<LoginForm> createState() => _LoginFormState();
}
class _LoginFormState extends State<LoginForm> {
final _formKey = GlobalKey<FormState>();
AutovalidateMode _mode = AutovalidateMode.disabled;
String? _validateUser(String? value) {
if (value == null || value.trim().isEmpty) return 'Username is required';
return null;
}
void _submit() {
if (_formKey.currentState!.validate()) {
debugPrint('Logging in');
} else {
setState(() => _mode = AutovalidateMode.always);
}
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
autovalidateMode: _mode,
child: Column(
children: [
TextFormField(
decoration: const InputDecoration(labelText: 'Username'),
validator: _validateUser,
),
ElevatedButton(onPressed: _submit, child: const Text('Log in')),
],
),
);
}
}The first tap on Log in calls validate(), which shows the errors. Because validation failed, setState switches the form to always. From then on, every rebuild re-validates, so an error clears as soon as the user fixes the field.
Using always here is safe because the user has already seen the errors. It would be a poor default for the first render.
Combining timing with validate()
Automatic validation and manual validation do not conflict. FormState.validate() always runs every validator in the form, whatever the mode. It returns true only if all of them return null.
This means the submit handler does not need to know which mode is active. It can call validate() every time. A field that has been validated automatically will simply be validated again.
void _submit() {
final form = _formKey.currentState!;
if (!form.validate()) return;
form.save();
}Resetting and the interaction flag
After a successful submit you may want to clear the form. FormState.reset() returns each field to its initial value and clears its error text. It also clears the "interacted with" flag. A reset field is quiet again under onUserInteraction, as if the user had never touched it.
If you use the submit-first pattern above, also set the mode back to disabled when you reset. Otherwise a form left on always would show a wall of "required" errors right after the reset.
void _clear() {
_formKey.currentState!.reset();
setState(() => _mode = AutovalidateMode.disabled);
}One caveat applies if you pass a controller. reset() restores the field's own initial value, and it also updates the controller's text to match. If your controller started with text, the field returns to that text, not to an empty string.
Choosing a mode
Use these questions to pick.
- Is the form short, with a single submit button?
disabledplus avalidate()call on submit is simple and predictable. - Does the user need feedback while typing, as with a password rule or a username that must be unique in format? Use
onUserInteraction. - Do you want a calm form that becomes helpful after the first failure? Use the submit-first pattern.
- Are you showing existing data that might already be wrong?
alwaysmakes the problems visible right away.
Common mistakes
- Using
alwaysas the default. Every empty field shows an error on the first frame. PreferonUserInteraction. - Expecting focus loss to trigger validation. Flutter has no built-in validate-on-blur. Leaving a field without changing it shows nothing. If you need that behavior, listen to a
FocusNodeand callvalidate()on the field's state yourself, or accept the default behavior. - Forgetting that
Formand field settings can differ. A field's ownautovalidateModewins over the form's. If errors do not appear when you expect, check the field first. - Doing slow work in a validator. Validators can run on many rebuilds. Do slow checks, such as "is this username taken", after submit and show the result as a server error.
- Not resetting the mode. After
reset(), a form still onalwaysimmediately shows errors for empty fields.
Timing flow
The diagram shows when a field's error appears in the submit-first pattern.
Exercise
A sign-up form has autovalidateMode: AutovalidateMode.onUserInteraction on the email field. A user taps into the empty field, then taps into the next field without typing anything. Does "Email is required" appear? What happens if they then type one character and delete it?
Show answer
No error appears after the first step. Focusing and leaving a field is not a value change, so the field has not been interacted with. After the user types a character and deletes it, the field counts as interacted with and the validator runs on each change. When the field is empty again, "Email is required" appears.
Exercise
In the submit-first pattern, why should _clear() set the mode back to AutovalidateMode.disabled after calling reset()?
Show answer
reset() restores the initial values, so the fields are empty again. If the form stays on always, the next rebuild runs every validator and shows "required" errors on fields the user has not touched. Setting the mode to disabled brings back the quiet state until the next failed submit.