Skip to content

Commit 1a6372f

Browse files
committed
Add phone validator
1 parent 18fa126 commit 1a6372f

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

lib/l10n/intl_en.arb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,6 @@
1717
"notEqualErrorText": "This field value must not be equal to {value}.",
1818
"numericErrorText": "Value must be numeric.",
1919
"requiredErrorText": "This field cannot be empty.",
20-
"urlErrorText": "This field requires a valid URL address."
20+
"urlErrorText": "This field requires a valid URL address.",
21+
"phoneErrorText": "This field requires a valid phone number."
2122
}

lib/src/form_builder_validators.dart

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,4 +314,13 @@ class FormBuilderValidators {
314314
!isDate(valueCandidate!)
315315
? errorText ?? FormBuilderLocalizations.current.dateStringErrorText
316316
: null;
317+
318+
/// [FormFieldValidator] that requires the field's value to be a valid phone number.
319+
static FormFieldValidator<String> phoneNumber({
320+
String? errorText,
321+
}) =>
322+
(valueCandidate) => true == valueCandidate?.isNotEmpty &&
323+
!isPhoneNumber(valueCandidate!)
324+
? errorText ?? FormBuilderLocalizations.current.phoneErrorText
325+
: null;
317326
}

lib/src/utils/validators.dart

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ RegExp _creditCard = RegExp(
1212
r'^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$',
1313
);
1414

15+
RegExp _phoneNumber = RegExp(r'^(\+?\d{0,1})?\(?\d{3}\)?[-.\s]\d{3}[-.\s]\d{4}$');
16+
1517
int _maxUrlLength = 2083;
1618

1719
/// check if the string [str] is an email
@@ -234,3 +236,8 @@ bool isDate(String str) {
234236
return false;
235237
}
236238
}
239+
240+
/// check if the string is a valid phone number
241+
bool isPhoneNumber(String str) {
242+
return _phoneNumber.hasMatch(str);
243+
}

0 commit comments

Comments
 (0)