简体   繁体   English

如何验证电话号码的 HTML 输入

[英]How to validate a HTML input for a phone number

Brief简介

Validate a UK Mobile Phone Number field in a HTML Form to take into account the following rules:验证 HTML 表单中的英国手机号码字段以考虑以下规则:

  1. Phone Number must begin 07电话号码必须以07开头
  2. Phone Number must not exceed 11 Digits电话号码不得超过 11 位
  3. Spaces are allowed (ignored).允许(忽略)空格。 I've found that Auto-Fill features sometimes save numbers like 0123456789 or 01234 456 789. I'd rather not cause the inconvenience to the user to reformat their auto-fill input.我发现自动填充功能有时会保存像 0123456789 或 01234 456 789 这样的数字。我不想给用户重新格式化他们的自动填充输入造成不便。

Valid Input Examples有效输入示例

  • 07234567890 07234567890
  • 07234 567 895 07234 567 895
  • 07 23 45 78 90 07 23 45 78 90

Where I am我在哪里

So far, I've only been able to validate my second point using:到目前为止,我只能使用以下方法验证我的第二点:

<input id="phonenum" type="tel" pattern="^\\d{11}$" required >

function validatePhoneNumber(){
    var e = document.getElementById('phonenum');
    var phoneNo;
    var firstLetter;
    var secondLetter;
    if(!e){
        return false;
    }

    phoneNo = e.value.replace(/ /g, ''); // remove spaces
    if(phoneNo.length != 11 ){
        return false;
    }

    firstLetter = phoneNo[0];
    secondLetter = phoneNo[1];
    if(firstLetter != "0" || secondLetter != "7"){
        return false;
    }

    return true;
}

如果你想使用正则表达式,你可以使用以下

^(0\W*7\W*(?:\d\W*){9})$

希望能帮助到你

 <input class="form-control" pattern="[789][0-9]{9}" type="text">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM