Skip to content

Commit f25348a

Browse files
committed
Add default
1 parent a4fc7e5 commit f25348a

File tree

4 files changed

+23
-0
lines changed

4 files changed

+23
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
* Add unique
4444
* Add ISBN
4545
* Add singleLine
46+
* Add defaultValue
4647

4748
## 10.0.1
4849
* Fix regression (include l10n files)

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ Available built-in helper validators:
5555
- `FormBuilderValidators.aggregate()` - runs the validators in parallel, collecting all errors.
5656
- `FormBuilderValidators.log()` - runs the validator and logs the value at a specific point in the validation chain.
5757
- `FormBuilderValidators.skipWhen()` - runs the validator and skips the validation when a certain condition is met.
58+
- `FormBuilderValidators.defaultValue()` - runs the validator using the default value when the provided value is null.
5859

5960
Available built-in type validators include:
6061

lib/src/form_builder_validators.dart

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,14 @@ class FormBuilderValidators {
119119
};
120120
}
121121

122+
/// [FormFieldValidator] that transforms the value to a default if it's null or empty before running the validator.
123+
/// * [defaultValue] is the default value to transform to.
124+
/// * [validator] is the validator to apply.
125+
static FormFieldValidator<T> defaultValue<T>(
126+
T defaultValue,
127+
FormFieldValidator<T> validator,
128+
) => (valueCandidate) => validator(valueCandidate ?? defaultValue);
129+
122130
/// [FormFieldValidator] that requires the field have a non-empty value.
123131
/// * [errorText] is the error message to display when the value is empty
124132
static FormFieldValidator<T> required<T>({

test/form_builder_validators_test.dart

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1208,4 +1208,17 @@ void main() {
12081208
expect(validator('The quick brown fox\n\rjumps'), isNotNull);
12091209
}),
12101210
);
1211+
1212+
testWidgets(
1213+
'FormBuilderValidators.defaultValue',
1214+
(WidgetTester tester) => testValidations(tester, (context) {
1215+
final validator = FormBuilderValidators.defaultValue<String>('default', FormBuilderValidators.alphabetical());
1216+
// Pass
1217+
expect(validator(null), isNull);
1218+
expect(validator('hello'), isNull);
1219+
// Fail
1220+
expect(validator('123'), isNotNull);
1221+
expect(validator(''), isNotNull);
1222+
}),
1223+
);
12111224
}

0 commit comments

Comments
 (0)