Sub topic 12
Validating fields against each other
This chapter assumes you can write a TextFormField with a validator, wrap fields in a Form with a GlobalKey<FormState>, and manage a TextEditingController in a State object. It also assumes you know the reusable Validator typedef from the previous chapter. If any of that is unfamiliar, review those chapters first.
Why a single-field validator is not enough
A validator receives one argument, the current value of its own field. It cannot see any other field. Some rules involve two or more fields:
- A confirmation password must equal the password.
- A maximum price must not be below the minimum price.
- A user must give an email address or a phone number, but not necessarily both.
The usual tool for this is a validator closure that reads the other field's TextEditingController. The closure is a function that captures variables from the surrounding scope. Because the controller holds the other field's live text, the closure sees the current value each time it runs.
Reading another controller inside a validator
The simplest cross-field rule is equality. This validator factory follows the same pattern as requiredField and minLength:
typedef Validator = String? Function(String? value);
Validator matchesField(TextEditingController other, String message) =>
(value) => value == other.text ? null : message;other.text is read when the validator runs, not when matchesField is called. This timing is what keeps the comparison current.
The stale error problem
A validator runs only when its own field is validated. That happens when the user edits that field, when Form.validate() runs, or when you validate the field yourself. Take this sequence:
- The user types
hunter22in Password. - The user types
hunter22in Confirm. No error is shown. - The user goes back and changes Password to
hunter23.
Confirm still shows no error. Its validator has not run since step 2, so the screen is out of date. Submitting would still catch the mismatch, because Form.validate() runs every validator. But the user sees a wrong state until then.
The fix is to revalidate the dependent field when the field it depends on changes. FormFieldState has its own validate() method, so you can revalidate one field without touching the rest of the form. To reach that state, give the dependent field a GlobalKey<FormFieldState<String>>.
A complete example
This program runs as shown. It defines the validators it needs, so it does not depend on earlier chapters' files.
import 'package:flutter/material.dart';
typedef Validator = String? Function(String? value);
Validator requiredField(String message) =>
(value) => (value == null || value.trim().isEmpty) ? message : null;
Validator minLength(int length) =>
(value) => (value ?? '').length < length
? 'Use at least $length characters'
: null;
Validator all(List<Validator> validators) => (value) {
for (final validator in validators) {
final error = validator(value);
if (error != null) return error;
}
return null;
};
Validator matchesField(TextEditingController other, String message) =>
(value) => value == other.text ? null : message;
void main() {
runApp(
const MaterialApp(
home: Scaffold(
body: Padding(padding: EdgeInsets.all(16), child: PasswordForm()),
),
),
);
}
class PasswordForm extends StatefulWidget {
const PasswordForm({super.key});
@override
State<PasswordForm> createState() => _PasswordFormState();
}
class _PasswordFormState extends State<PasswordForm> {
final _formKey = GlobalKey<FormState>();
final _confirmKey = GlobalKey<FormFieldState<String>>();
final _password = TextEditingController();
final _confirm = TextEditingController();
@override
void dispose() {
_password.dispose();
_confirm.dispose();
super.dispose();
}
void _submit() {
if (_formKey.currentState!.validate()) {
debugPrint('Password accepted');
}
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: _password,
obscureText: true,
textInputAction: TextInputAction.next,
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(labelText: 'Password'),
validator: all([
requiredField('Password is required'),
minLength(8),
]),
onChanged: (_) {
if (_confirm.text.isNotEmpty) {
_confirmKey.currentState?.validate();
}
},
),
TextFormField(
key: _confirmKey,
controller: _confirm,
obscureText: true,
textInputAction: TextInputAction.done,
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(labelText: 'Confirm password'),
onFieldSubmitted: (_) => _submit(),
validator: all([
requiredField('Confirm your password'),
matchesField(_password, 'Passwords do not match'),
]),
),
ElevatedButton(onPressed: _submit, child: const Text('Save')),
],
),
);
}
}Three details matter here:
- The
if (_confirm.text.isNotEmpty)guard stops the password field from showing a "Confirm your password" error before the user has reached the second field. - The
?.aftercurrentStateis needed because the state is null until the field has been built. all()puts the cheap "required" check before the comparison, so an empty confirmation shows the more useful message.
Ranges: one field depends on another
The same pattern handles ordered values. The rule below is placed on the maximum field and reads the minimum field's controller:
Validator atLeastField(TextEditingController min, String message) => (value) {
final lo = int.tryParse(min.text.trim());
final hi = int.tryParse((value ?? '').trim());
if (lo == null || hi == null) return null;
return hi < lo ? message : null;
};If either value fails to parse, the validator returns null. The reason is that each field has its own validator to report "not a number", and this validator should report only the relationship between two valid values. Mixing the two concerns produces misleading messages, such as telling the user that max is too small when max is simply empty.
The minimum field needs the same revalidation call as the password example. Give the maximum field a GlobalKey<FormFieldState<String>> and call its validate() from the minimum field's onChanged.
Group rules: at least one of several fields
Some rules do not belong to any single field. "Provide an email or a phone number" is one example. A validator can only attach its message to one field, so choose the field where the error reads most naturally. Here that is the second one:
Validator emailOrPhone(TextEditingController email, String message) =>
(value) {
final hasPhone = (value ?? '').trim().isNotEmpty;
final hasEmail = email.text.trim().isNotEmpty;
return (hasPhone || hasEmail) ? null : message;
};Attach it to the phone field, with the email controller passed in. If the email field also needs to clear the phone error when the user starts typing, give the phone field a GlobalKey<FormFieldState<String>> and revalidate from the email field's onChanged, as before.
If the rule spans many fields, a better design is a separate check in _submit after validate() passes, with the message shown through a banner or a SnackBar. That keeps the field validators simple.
Choosing an approach
| Approach | Use it when | Drawback |
|---|---|---|
| Validator closure over a controller | Any rule that compares against another text field | Only runs when its own field is validated |
| Closure plus `FormFieldState.validate()` from `onChanged` | The error must update as soon as the other field changes | Needs a `GlobalKey` per dependent field |
| Check only at submit | The rule is expensive or spans many fields | Error appears late |
| Validate the whole form on every change | Very small forms | Untouched fields show errors early |
Common mistakes
- Comparing trimmed with untrimmed text. If you trim one side, trim both. Passwords are usually compared exactly, so do not trim them at all.
- Forgetting to dispose the controllers. Cross-field validation makes several controllers live at once. Dispose each one in
dispose(). - Creating the
GlobalKeyinbuild. A key created on every build gives the field a new identity each time and discards its state. Create keys once, asStatefields. - Revalidating from inside a validator. Calling
validate()on another field from within a validator can loop or trigger a rebuild during a build. Trigger revalidation from event callbacks such asonChanged. - Mutating the other field in a validator. A validator should only read and return. Side effects belong in callbacks.
Exercise
A form has Start and End fields holding whole numbers. End has the validator atLeastField(_start, 'End must not be before start'). A user enters Start = 5 and End = 8, then changes Start to 20. No error appears on End until the user taps Submit. Why does this happen, and what is the smallest change that fixes it?
Show answer
End's validator only runs when End itself is validated, and editing Start does not validate End. Give the End field a GlobalKey<FormFieldState<String>> (created once as a State field and passed as key: to its TextFormField), then add onChanged: () => endKey.currentState?.validate() to the Start field. You may also guard it with a check that End's text is not empty, so an untouched End field is not flagged early. Submit still catches the error because Form.validate() runs every validator.
Exercise
Why does matchesField take the TextEditingController instead of a String such as _password.text?
Show answer
A String is a snapshot taken when matchesField is called, usually during build, and it goes stale as soon as the user types. The controller is a live object, so other.text is read at the moment the validator runs and always reflects the current input.