Flutter-使用Regex验证电话号码 [英] Flutter - Validate a phone number using Regex

查看:99
本文介绍了Flutter-使用Regex验证电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的移动应用程序中,我试图使用 regex 验证电话号码。以下是条件。

In my futter mobile app, I am trying to validate a phone number using regex. Below are the conditions.


  1. 电话号码必须包含10位数字。

  2. 如果国家/地区代码为我们使用时,可以是12位数字。 (国家代码示例:+12、012)

  3. 数字之间不允许有空格或字符

简单来说,这是唯一的有效电话号码

In simple terms, here is are the only "valid" phone numbers

0776233475 +94776233475 094776233475

下面是我尝试过的方法,但确实可以

Below is what I tried, but it do not work.

String _phoneNumberValidator(String value) {
    Pattern pattern =
        r'/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/';
    RegExp regex = new RegExp(pattern);
    if (!regex.hasMatch(value))
      return 'Enter Valid Phone Number';
    else
      return null;
  }

我该如何解决?

推荐答案

您可以将第一部分设为与 + 或0后跟9匹配的可选部分。然后匹配10位数字:

You could make the first part optional matching either a + or 0 followed by a 9. Then match 10 digits:

^(?:[+0]9)?[0-9]{10}$




  • ^ 字符串的开头

  • (?:[+ 0] 9)?可选地匹配 + 0 后跟9

  • [0-9] {10} 匹配10位数字

  • $ 字符串结尾

    • ^ Start of string
    • (?:[+0]9)? Optionally match a + or 0 followed by 9
    • [0-9]{10} Match 10 digits
    • $ End of string
    • 正则表达式演示

      这篇关于Flutter-使用Regex验证电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆