Sub topic 11
Building reusable validators
This chapter assumes you can write a TextFormField with a validator, wrap fields in a Form, and call validate() through a GlobalKey<FormState>. You should also be comfortable with nullable types, closures, and function types in Dart. Here you will move rules out of individual fields and into small functions that you can name, combine, and test.
Why inline validators stop scaling
A validator is a function from String? to String?. It returns an error message, or null when the value is acceptable. Writing the function inline works for one field:
validator: (value) {
if (value == null || value.trim().isEmpty) return 'Email is required';
if (!value.contains('@')) return 'Enter a valid email address';
return null;
},A real form repeats the "required" check on every field. The length and format checks show up again on the next screen. Copying them leads to messages that drift apart and to fixes that reach only some of the copies.
Because a validator is an ordinary function value, you can build validators with functions. The idea has three parts:
- Name the function type once.
- Write small functions that return a validator, called factories, each carrying one rule.
- Write a combinator that turns a list of validators into one.
Naming the type and writing factories
A typedef gives the function type a short name. Each factory takes its configuration (a message, a length) and returns a closure that remembers it.
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 pattern(RegExp regex, String message) =>
(value) => regex.hasMatch(value ?? '') ? null : message;requiredField('Email is required') is not an error message. It is a function waiting to be called with a value. TextFormField.validator expects exactly that type, so you can pass the result straight in.
Each rule treats null as an empty string. TextFormField passes null to the validator when the field has no text, so a rule that calls value.length directly will throw.
Combining rules with all()
Fields usually need several rules, and the user should see one message at a time. The combinator runs validators in order and returns the first error:
Validator all(List<Validator> validators) => (value) {
for (final validator in validators) {
final error = validator(value);
if (error != null) return error;
}
return null;
};Order matters. Put requiredField first so an empty field says "required" instead of "use at least 8 characters". Put cheap checks before expensive ones, such as a long regular expression.
If the name all clashes with something in your project, call it compose or firstError. The name has no special meaning to Flutter.
A small validator library
Here is a complete file you can run. It adds an optional wrapper and an email rule, and uses them in a form.
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 pattern(RegExp regex, String message) =>
(value) => regex.hasMatch(value ?? '') ? null : message;
Validator optional(Validator inner) =>
(value) => (value == null || value.trim().isEmpty) ? null : inner(value);
Validator all(List<Validator> validators) => (value) {
for (final validator in validators) {
final error = validator(value);
if (error != null) return error;
}
return null;
};
final _emailPattern = RegExp(r'^[^@\s]+@[^@\s]+\.[^@\s]+$');
Validator email() =>
pattern(_emailPattern, 'Enter a valid email address');
void main() => runApp(const MaterialApp(home: Scaffold(body: ProfileForm())));
class ProfileForm extends StatefulWidget {
const ProfileForm({super.key});
@override
State<ProfileForm> createState() => _ProfileFormState();
}
class _ProfileFormState extends State<ProfileForm> {
final _formKey = GlobalKey<FormState>();
void _submit() {
if (_formKey.currentState!.validate()) {
debugPrint('Valid');
}
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [
TextFormField(
decoration: const InputDecoration(labelText: 'Email'),
keyboardType: TextInputType.emailAddress,
validator: all([requiredField('Email is required'), email()]),
),
TextFormField(
decoration: const InputDecoration(labelText: 'Backup email'),
keyboardType: TextInputType.emailAddress,
validator: optional(email()),
),
ElevatedButton(onPressed: _submit, child: const Text('Save')),
],
),
);
}
}The second field is optional, but it must still be valid when filled in. optional skips the inner rule for empty input and applies it otherwise. Writing this as a wrapper keeps the individual rules simple, because none of them has to know whether the field is required.
The email expression only checks the shape: something, an @, something, a dot, something. Whether an address really exists can only be settled by sending mail to it, so a stricter pattern mostly rejects valid addresses.
Where to build the validators
all([...]) runs every time build runs, so each rebuild creates new closures. That is cheap, and Flutter does not compare validator identity, so it causes no extra work.
If you prefer to build each one once, store it in a final field of the State class, or in a top-level constant-like variable such as final _passwordRules = all([...]);. You cannot use const here, because closures created by factory calls are not compile-time constants.
Messages and localization
The examples above pass a message string into each factory. That is simple, but it breaks when the app is translated, because the string is fixed when the validator is created, not when it is shown.
Two common fixes:
- Build the validators inside
build, whereAppLocalizations.of(context)is available, and pass the translated text in. - Have the factory accept a function,
String Function() message, that is called when the rule fails.
The first fix needs no change to the library. Pick it unless validators must be created outside the widget tree.
Testing validators on their own
A validator is a plain function, so you can test it without building any widgets. This is the main practical gain from the pattern.
import 'package:flutter_test/flutter_test.dart';
// Assumes the validator library above is imported.
void main() {
group('all', () {
final validate = all([requiredField('Required'), minLength(8)]);
test('returns the first failing message', () {
expect(validate(''), 'Required');
expect(validate('abc'), 'Use at least 8 characters');
});
test('returns null when every rule passes', () {
expect(validate('long enough'), isNull);
});
test('treats null like empty input', () {
expect(validate(null), 'Required');
});
});
test('optional skips empty input only', () {
final validate = optional(email());
expect(validate(''), isNull);
expect(validate('nope'), 'Enter a valid email address');
});
}These tests run in milliseconds. A widget test for the same behavior has to pump a widget tree, tap buttons, and look for text.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Calling `value.length` without a null check | Throws on an untouched field | Use `(value ?? '')` or `value?.length ?? 0` |
| Passing `requiredField('x')()` or calling the factory result early | Type error or a `String?` where a function is expected | Pass the returned function itself |
| Putting `minLength` before `requiredField` | Empty field shows a length message | Order rules from most to least basic |
| Forgetting `trim()` in the required check | A field with only spaces passes | Trim before testing for empty |
| Returning `''` instead of `null` for valid input | `FormField` treats an empty string as an error and marks the field invalid | Return `null` for valid |
The last row catches many people. FormFieldState treats any non-null return as an error, even an empty string. The field then shows an error state with no visible message.
Exercise
Write a maxLength(int length) factory that returns the message 'Use at most N characters' when the value is longer than length. Then write the validator for a username field that is required, at least 3 characters, and at most 20 characters, in a sensible order. What does that validator return for the value null?
Show answer
The factory is Validator maxLength(int length) => (value) => (value ?? '').length > length ? 'Use at most $length characters' : null;. The username validator is all([requiredField('Username is required'), minLength(3), maxLength(20)]). Required comes first so an empty field gets the basic message. For null, requiredField returns 'Username is required', and all stops there and returns that message.