Sub topic 11
Building Reusable Validators
Assume you know Dart nullable types, closures, StatefulWidget, and the basic use of Form and TextFormField. A validator is a function that receives a field's current value and returns either an error message or null. Returning null means the value is valid.
Writing validators directly inside every TextFormField works for small forms, but repeated rules become difficult to keep consistent. Reusable validators let you define each rule once and combine rules for different fields.
Define a validator type
A type alias gives the validator function a readable name:
typedef Validator = String? Function(String? value);
Validator requiredField(String message) {
return (value) {
if (value == null || value.trim().isEmpty) {
return message;
}
return null;
};
}
Validator minLength(int length) {
return (value) {
if ((value ?? '').length < length) {
return 'Use at least $length characters';
}
return null;
};
}
Validator all(List<Validator> validators) {
return (value) {
for (final validator in validators) {
final error = validator(value);
if (error != null) {
return error;
}
}
return null;
};
}requiredField treats whitespace-only input as empty. minLength uses an empty string when its nullable input is null. The all function runs validators in order and returns the first error. If every validator returns null, all also returns null.
Use validators in a form
Pass a composed validator to the validator property:
TextFormField(
decoration: const InputDecoration(labelText: 'Password'),
obscureText: true,
validator: all([
requiredField('Password is required'),
minLength(8),
]),
),The order matters. The user sees “Password is required” before a length error. This produces a clearer correction path.
Understand the validation flow
When FormState.validate() runs, Flutter asks each registered form field to run its validator. The first non-null message becomes that field's error text.
Common errors
- Returning an empty string instead of
null. An empty string still means validation failed. - Forgetting to handle
null. A field can providenullwhen it has no value. - Checking length before trimming when spaces should not count.
- Returning every error at once. The validator contract expects one message, so composition should normally stop at the first failure.
- Performing network requests inside a validator. Asynchronous server checks belong in submission logic, not in a synchronous validator.
The same pattern can support email, numeric range, and password rules. Keep messages specific enough to tell the user how to correct the value.
Exercise
What does all([requiredField('Name is required'), minLength(3)]) return when the value is an empty string?
Show answer
It returns Name is required, because the required validator fails first and all stops at the first error.