Regex用于广泛的电话号码验证

Regex for extensive phone number validation

本文关键字:电话号码 验证 用于 Regex      更新时间:2023-09-26

我有许多规则需要应用于电话号码输入字段,以下是我的尝试:

var positive_checks = new Array(
    /^[0-9]{8}$/g    // 1. Must have 8 digits exactly
);
var negative_checks = new Array(
    /^[0147]/g,      // 2. Must not start with 0,1,4 or 7
    /^[9]{3}/g,      // 3. Must not start with 999
    /(.)''1*$/g      // 4. Must not be all the same number
);
for (i in positive_checks) {
    if (str.search(positive_checks[i]) < 0) {
        return false;
    }
}
for (i in negative_checks) {
    if (str.search(negative_checks[i]) >= 0) {
        return false;
    }
}

除了第4条规则外,所有的规则都在起作用,我不完全理解它,只是它以某种方式使用了反向引用。我认为有人提到环境需要允许反向引用,Javascript就是这样的环境吗?

第二,我有兴趣尝试并修改所有规则,所以我只需要有一个规则数组和循环,而不需要检查阴性检查,这在每个实例中都可能吗?最终,我正在寻找一个Javascript解决方案,但在我看来,能够对所有4个代码使用regex会使其看起来更好,而作为表单验证逻辑意味着性能在这里并不是一个真正的问题。

你的第四条规则可能不起作用,因为你的反向引用有双反斜杠,我也会锚定它,并将*量词改为+,意思是"一次或多次"

/^(.)'1+$/g

说明:

^      # the beginning of the string
(      # group and capture to '1:
  .    #   any character except 'n
)      # end of '1
  '1+  #   what was matched by capture '1 (1 or more times)
$      # before an optional 'n, and the end of the string

一个将验证您所有需求的一行代码:

var re = /^(?=.{8}$)(?!999|[0147]|(.)'1+)[0-9]+$/

使用regexr.com/39khr并将鼠标悬停在表达式的不同部分以查看它们的作用。

由于你没有说什么不起作用,即:举一个应该是真的或相反的假数字的例子,很难给你一个答案。