Skip to content

Commit 8602975

Browse files
committed
Added option to allowEmpty in minLength and maxLength validations. Closes #259
1 parent 14f41a9 commit 8602975

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

lib/src/form_builder_validators.dart

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,13 @@ class FormBuilderValidators {
7272
/// greater than or equal to the provided minimum length.
7373
static FormFieldValidator minLength(
7474
num minLength, {
75+
bool allowEmpty = false,
7576
String errorText,
7677
}) {
7778
return (valueCandidate) {
79+
if (allowEmpty && (valueCandidate == null || valueCandidate?.length == 0))
80+
return errorText ??
81+
"Value must have a length greater than or equal to $minLength";
7882
if (valueCandidate != null && valueCandidate.length < minLength) {
7983
return errorText ??
8084
"Value must have a length greater than or equal to $minLength";
@@ -88,8 +92,13 @@ class FormBuilderValidators {
8892
static FormFieldValidator maxLength(
8993
num maxLength, {
9094
String errorText,
95+
bool allowEmpty = false,
9196
}) {
9297
return (valueCandidate) {
98+
if (allowEmpty && (valueCandidate == null || valueCandidate?.length == 0))
99+
return errorText ??
100+
"Value must have a length greater than or equal to $minLength";
101+
93102
if (valueCandidate != null && valueCandidate.length > maxLength) {
94103
return errorText ??
95104
"Value must have a length less than or equal to $maxLength";
@@ -111,14 +120,15 @@ class FormBuilderValidators {
111120
}
112121

113122
/// [FormFieldValidator] that requires the field's value to be a valid url.
114-
static FormFieldValidator url(
115-
{String errorText = "This field requires a valid URL address.",
116-
List<String> protocols = const ['http', 'https', 'ftp'],
117-
bool requireTld = true,
118-
bool requireProtocol = false,
119-
bool allowUnderscore = false,
120-
List<String> hostWhitelist = const [],
121-
List<String> hostBlacklist = const []}) {
123+
static FormFieldValidator url({
124+
String errorText = "This field requires a valid URL address.",
125+
List<String> protocols = const ['http', 'https', 'ftp'],
126+
bool requireTld = true,
127+
bool requireProtocol = false,
128+
bool allowUnderscore = false,
129+
List<String> hostWhitelist = const [],
130+
List<String> hostBlacklist = const [],
131+
}) {
122132
return (valueCandidate) {
123133
if (valueCandidate != null && valueCandidate.isNotEmpty) {
124134
if (!isURL(valueCandidate,

0 commit comments

Comments
 (0)