Skip to content

Commit 5679930

Browse files
committed
Added two validators for min & max words count
1 parent 7a680dd commit 5679930

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

lib/localization/l10n.dart

Lines changed: 20 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

lib/src/form_builder_validators.dart

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,48 @@ class FormBuilderValidators {
172172
};
173173
}
174174

175+
/// [FormFieldValidator] that requires the words count of the field's value to be
176+
/// greater than or equal to the provided minimum count.
177+
static FormFieldValidator<String> minWordsCount(
178+
int minCount, {
179+
bool allowEmpty = false,
180+
String? errorText,
181+
}) {
182+
assert(minCount > 0);
183+
return (valueCandidate) {
184+
int valueWordsCount = 0;
185+
186+
if (valueCandidate != null) {
187+
if (valueCandidate.isEmpty) {
188+
valueWordsCount = 0;
189+
} else {
190+
valueWordsCount = valueCandidate.split(' ').length;
191+
}
192+
}
193+
194+
return valueWordsCount < minCount && (!allowEmpty || valueWordsCount > 0)
195+
? errorText ??
196+
FormBuilderLocalizations.current.minWordsCountErrorText(minCount)
197+
: null;
198+
};
199+
}
200+
201+
/// [FormFieldValidator] that requires the words count of the field's value to be
202+
/// less than or equal to the provided maximum count.
203+
static FormFieldValidator<String> maxWordsCount(
204+
int maxCount, {
205+
String? errorText,
206+
}) {
207+
assert(maxCount > 0);
208+
return (valueCandidate) {
209+
int valueWordsCount = valueCandidate?.split(' ').length ?? 0;
210+
return null != valueCandidate && valueWordsCount > maxCount
211+
? errorText ??
212+
FormBuilderLocalizations.current.maxWordsCountErrorText(maxCount)
213+
: null;
214+
};
215+
}
216+
175217
/// [FormFieldValidator] that requires the field's value to be a valid email address.
176218
static FormFieldValidator<String> email({
177219
String? errorText,

0 commit comments

Comments
 (0)