验证 phone 以 080、081、090、070、091 开头的号码

Validate phone number start with 080, 081, 090, 070, 091

我想验证 phone 号码前缀和位数。

phone 号码的长度为 11 位数字(仅限数字)。 前缀必须以以下任一前缀开头:080、081、090、091、070,最大为 11 位。

我在 javascript 中使用以下代码放置了一个验证码来验证 phone 数字,它工作正常。

**Phone number 11 digits validation code below;**
} else if (form.usercheck1.value.length<11 || 
   form.usercheck1.value.length>11) { alert("phone number should be 11 digits!");
}

但我需要帮助来验证 phone prifix。 任何帮助将不胜感激。

我下面的完整 javascript 代码;

/* myScript.js */
function check(form) /*function to check userid & password*/ {
  /*the following code checkes whether the entered userid and password are matching*/
  if (form.usercheck1.value == "1234" ||
    form.usercheck1.value == "12345")  {
      alert("An account already exist with this phone number! \nKindly login to proceed.") // displays error message
    } else if (form.usercheck1.value.length < 11 || form.usercheck1.value.length > 11) {
      alert("phone number should be 11 digits!");
    } else {
      window.location.replace('https://www.google.com')
      /*opens the target page while Id & password matches*/
    }
  }
}

您可以使用这种模式:^0([89][01]|70)\d{8}$

这会检查前缀和总共 11 位数字。

注意:你说最多 11 位数字,但当我阅读你的代码时,你似乎正好需要 11 位数字,上面的模式恰好适用于 11 位数字。如果你想让它最多 11 位数字,你可以使用这个:^0([89][01]|70)\d{0,8}$

<!DOCTYPE html>
<html>
  <body>
  <form>
    <label for="phone_number">Phone number: </label>
    <input type="text" id="phone_number" name="phone_number" pattern="^0([89][01]|70)\d{8}$" title="Maximum length is 11 and Phone number must start with one of 080, 081, 090, 091 or 070 And must be all numeric">
    <input type="submit" value="Submit">
  </form>
  </body>
</html>

你真的需要为此使用正则表达式吗??

你觉得下面哪个更容易理解?

/^0(?:[89][01]|70)/.test(input)
['080', '081', '090', '070', '091'].includes(input.substring(0,3))

除非列表变得很长,并且有明确的模式,否则我会选择不在这里使用神秘的正则表达式。