|
| 1 | +import 'dart:async'; |
| 2 | + |
1 | 3 | import 'package:flutter/material.dart';
|
2 | 4 | import '../form_builder_validators.dart';
|
3 | 5 |
|
@@ -43,6 +45,62 @@ class FormBuilderValidators {
|
43 | 45 | };
|
44 | 46 | }
|
45 | 47 |
|
| 48 | + /// [FormFieldValidator] that transforms the value before applying the validator. |
| 49 | + static FormFieldValidator transform<T>( |
| 50 | + FormFieldValidator<T> validator, |
| 51 | + T Function(T? value) transformer, |
| 52 | + ) { |
| 53 | + return (valueCandidate) { |
| 54 | + final transformedValue = transformer(valueCandidate); |
| 55 | + return validator(transformedValue); |
| 56 | + }; |
| 57 | + } |
| 58 | + |
| 59 | + /// [FormFieldValidator] that debounces the validation. |
| 60 | + /// * [duration] is the duration to wait before running the validation. |
| 61 | + static FormFieldValidator<T> debounce<T>({ |
| 62 | + required Duration duration, |
| 63 | + required FormFieldValidator<T> validator, |
| 64 | + }) { |
| 65 | + Timer? debounceTimer; |
| 66 | + String? result; |
| 67 | + |
| 68 | + return (valueCandidate) { |
| 69 | + debounceTimer?.cancel(); |
| 70 | + debounceTimer = Timer(duration, () { |
| 71 | + result = validator(valueCandidate); |
| 72 | + }); |
| 73 | + |
| 74 | + return result; |
| 75 | + }; |
| 76 | + } |
| 77 | + |
| 78 | + /// [FormFieldValidator] that retries the validation. |
| 79 | + /// * [times] is the number of times to retry the validation. |
| 80 | + /// * [duration] is the duration to wait before retrying the validation. |
| 81 | + static FormFieldValidator<T> retry<T>({ |
| 82 | + required int times, |
| 83 | + required Duration duration, |
| 84 | + required FormFieldValidator<T> validator, |
| 85 | + }) { |
| 86 | + int retries = 0; |
| 87 | + String? result; |
| 88 | + |
| 89 | + return (valueCandidate) { |
| 90 | + if (retries < times) { |
| 91 | + result = validator(valueCandidate); |
| 92 | + if (result != null) { |
| 93 | + retries++; |
| 94 | + Future.delayed(duration, () { |
| 95 | + result = validator(valueCandidate); |
| 96 | + }); |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + return result; |
| 101 | + }; |
| 102 | + } |
| 103 | + |
46 | 104 | /// [FormFieldValidator] that requires the field have a non-empty value.
|
47 | 105 | static FormFieldValidator<T> required<T>({
|
48 | 106 | String? errorText,
|
|
0 commit comments