File tree Expand file tree Collapse file tree 3 files changed +36
-0
lines changed Expand file tree Collapse file tree 3 files changed +36
-0
lines changed Original file line number Diff line number Diff line change @@ -50,6 +50,7 @@ Available built-in helper validators:
50
50
51
51
- ` FormBuilderValidators.compose() ` - runs each validator against the value provided.
52
52
- ` 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.
53
54
54
55
Available built-in type validators include:
55
56
Original file line number Diff line number Diff line change @@ -23,6 +23,26 @@ class FormBuilderValidators {
23
23
};
24
24
}
25
25
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
+
26
46
/// [FormFieldValidator] that requires the field have a non-empty value.
27
47
static FormFieldValidator <T > required < T > ({
28
48
String ? errorText,
Original file line number Diff line number Diff line change @@ -965,4 +965,19 @@ void main() {
965
965
expect (validator (4 ), isNotNull);
966
966
}),
967
967
);
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
+ );
968
983
}
You can’t perform that action at this time.
0 commit comments