Sub topic 12
Validating Fields Against Each Other
Assume you know Dart nullable values, closures, StatefulWidget, Form, and TextFormField. This chapter focuses on rules that need more than one field, such as confirming a password or checking that a start date comes before an end date.
A field validator receives only its own value. For a cross-field rule, the validator must also read another field's value. A TextEditingController gives you that value through its text property.
Comparing two fields
A confirmation field should usually apply both of these rules:
- It must not be empty.
- It must match the original field.
The validator can read the password controller while validating the confirmation field:
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: PasswordForm()));
}
class PasswordForm extends StatefulWidget {
const PasswordForm({super.key});
@override
State<PasswordForm> createState() => _PasswordFormState();
}
class _PasswordFormState extends State<PasswordForm> {
final _formKey = GlobalKey<FormState>();
final _password = TextEditingController();
final _confirm = TextEditingController();
final _confirmKey = GlobalKey<FormFieldState<String>>();
@override
void dispose() {
_password.dispose();
_confirm.dispose();
super.dispose();
}
void _submit() {
if (_formKey.currentState!.validate()) {
debugPrint('Password is ready to submit');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Create password')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: _password,
obscureText: true,
decoration: const InputDecoration(labelText: 'Password'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Password is required';
}
if (value.length < 8) {
return 'Use at least 8 characters';
}
return null;
},
onChanged: (_) => _confirmKey.currentState?.validate(),
),
TextFormField(
key: _confirmKey,
controller: _confirm,
obscureText: true,
decoration: const InputDecoration(
labelText: 'Confirm password',
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please confirm your password';
}
if (value != _password.text) {
return 'Passwords do not match';
}
return null;
},
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _submit,
child: const Text('Create account'),
),
],
),
),
),
);
}
}The confirmation validator reads _password.text whenever Flutter validates that field. The comparison therefore uses the current password, not the password from when the widget was first built.
_confirmKey is a key for the individual FormField. Calling validate() on its state updates only the confirmation field. The password field calls this method when its value changes, so changing the original password immediately rechecks the confirmation.
Avoiding common errors
Do not compare controllers directly. _confirm == _password compares controller objects, not their text. Compare _confirm.text with _password.text, or compare the validator's value with _password.text.
Dispose every controller created by the state object. Also consider whether the second field should be revalidated when the first field changes. Without that step, the interface may keep showing an old result until the user submits or edits the confirmation field.
The same pattern works for other dependent values:
- Confirming an email address.
- Checking that a minimum value is below a maximum value.
- Comparing a selected country with a region.
- Checking that an end date follows a start date.
Exercise
Why does the confirmation field need to be revalidated when the password changes?
Show answer
Its validity depends on the password value, so a previous validation result may become incorrect when the password changes.