Skip to content

Commit 2e7070f

Browse files
committed
Add or
1 parent 3536f88 commit 2e7070f

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ Available built-in helper validators:
5050

5151
- `FormBuilderValidators.compose()` - runs each validator against the value provided.
5252
- `FormBuilderValidators.conditional()` - conditionally runs a validator against the value provided.
53+
- `FormBuilderValidators.or()` - runs each validator against the value provided and passes when any works.
5354

5455
Available built-in type validators include:
5556

lib/src/form_builder_validators.dart

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,26 @@ class FormBuilderValidators {
2323
};
2424
}
2525

26+
/// [FormFieldValidator] that is composed of other [FormFieldValidator]s.
27+
/// Each validator is run against the [FormField] value and if any returns a
28+
/// null result validation passes
29+
static FormFieldValidator<T> or<T>(
30+
List<FormFieldValidator<T>> validators,
31+
) {
32+
return (valueCandidate) {
33+
String? errorResult;
34+
for (final validator in validators) {
35+
final validatorResult = validator.call(valueCandidate);
36+
if (validatorResult == null) {
37+
return null;
38+
} else {
39+
errorResult = validatorResult;
40+
}
41+
}
42+
return errorResult;
43+
};
44+
}
45+
2646
/// [FormFieldValidator] that requires the field have a non-empty value.
2747
static FormFieldValidator<T> required<T>({
2848
String? errorText,

test/form_builder_validators_test.dart

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -965,4 +965,19 @@ void main() {
965965
expect(validator(4), isNotNull);
966966
}),
967967
);
968+
969+
testWidgets(
970+
'FormBuilderValidators.or',
971+
(WidgetTester tester) => testValidations(tester, (context) {
972+
final validator = FormBuilderValidators.or([
973+
FormBuilderValidators.numeric(),
974+
FormBuilderValidators.startsWith(prefix: 'Hello'),
975+
]);
976+
// Pass
977+
expect(validator('123'), isNull);
978+
expect(validator('Hello world'), isNull);
979+
// Fail
980+
expect(validator('123 hello'), isNotNull);
981+
}),
982+
);
968983
}

0 commit comments

Comments
 (0)