Skip to content

Commit 30c3947

Browse files
implement conditional validator if
1 parent 8fab069 commit 30c3947

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import '../constants.dart';
2+
3+
/// This function returns a validator that conditionally validates the user input.
4+
/// If `condition` applied to the user input evaluates to true, the user input is
5+
/// validated by `v`. Otherwise, it is automatically considered valid.
6+
Validator<T> validateIf<T extends Object?>(
7+
bool Function(T value) condition, Validator<T> v) {
8+
return (T value) => condition(value) ? v(value) : null;
9+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import 'package:flutter_test/flutter_test.dart';
2+
import 'package:form_builder_validators/form_builder_validators.dart';
3+
import 'package:form_builder_validators/new_api_prototype/core_validators/conditional_validators.dart';
4+
5+
const String errorGt = 'error gt';
6+
Validator<num> gt(num target) {
7+
return (num v) {
8+
return v > target ? null : errorGt;
9+
};
10+
}
11+
12+
void main() {
13+
group('Validator: validateIf', () {
14+
test('Should check if a number is greater than 10 if it is an even int',
15+
() {
16+
// Only even integers will be validated: ... 0, 2, 4 ...
17+
final Validator<num> v =
18+
validateIf((num v) => v is int && v % 2 == 0, gt(10));
19+
20+
expect(v(2.3), isNull);
21+
22+
expect(v(8), errorGt);
23+
expect(v(10), errorGt);
24+
expect(v(12), isNull); // This is null because it is valid
25+
expect(v(13), isNull); // This is null because it was not validated.
26+
});
27+
});
28+
}

0 commit comments

Comments
 (0)