我正在开发一个可以验证电话号码的 flutter 应用程序。我想使用正则表达式进行验证。所有数字均应以 +260 开头。第 4 位数字可以是 7 或 9,其余 8 位数字应该是 0-9 之间的任何数字。你能帮我实现这个目标吗?例如,完整数字应为 (+260(7 或 9)********)。我尝试在代码中使用以下表达式,但它不起作用。
validator: (value) {
if (value!.isEmpty) {
return 'Phone number cannot be empty';
}
if (!RegExp(r'^\+260[79][567]\d{7}$').hasMatch(value)) {
return 'Enter valid number';
}
return null;
},
使用
^\+(?:\d\s?){6,14}\d$
解释
NODE EXPLANATION
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
\+ '+'
--------------------------------------------------------------------------------
(?: group, but do not capture (between 6 and
14 times (matching the most amount
possible)):
--------------------------------------------------------------------------------
\d digits (0-9)
--------------------------------------------------------------------------------
\s? whitespace (\n, \r, \t, \f, and " ")
(optional (matching the most amount
possible))
--------------------------------------------------------------------------------
){6,14} end of grouping
--------------------------------------------------------------------------------
\d digits (0-9)
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
^+260[79]\d{8}$
因此,完整的正则表达式确保字符串以“+260”开头,后跟 7 或 9,然后紧跟 8 位数字。
您可以在代码中使用此正则表达式进行验证。如果您遇到任何问题,请告诉我,我可以进一步帮助您!