验证电话号码字段?

时间:2015-05-26 04:36:46

标签: html html5 validation

我需要在我的表单中验证一个电话号码字段我的条件是数字可能是8位数或10位数除此之外应该通知我尝试的方式就像这样可以吗?

<input class="form-control" name="phone_no" id="phone_no" placeholder="Enter a Phone Number" type="tel"  title='Phone Number(Format:04xxxxxxx)' size="10" min="8" max="10" required>

或如何使用patter属性来实现这个目标?pattern='\d{3}\d{4}\d{4}' 像我这样使用但我需要检查它是否介于8和10之间,而不是8和10以上应该给出错误或通知!

5 个答案:

答案 0 :(得分:0)

我写了一个javascript函数,它将检测该号码是澳大利亚固定电话还是澳大利亚移动电话,并相应地格式化它们。 对于固定电话和移动电话,它接受+61,并且需要固定电话的区号。

如果您认为其缺少功能

,请随时添加
    function validatePhoneNumber(phone_number){
        var formatted = "";
        //remove all non-digits
        phone_number = phone_number.replace(/\D/g,'');
        //if number starts with 61, replace 61 with 0
        if (phone_number.match(/^61/)){
              phone_number = "0"+phone_number.slice(2);
        }
        if (phone_number.match(/^04/)){
            if (phone_number.length === 10){
                var formatted = phone_number.replace(/(\d{4})(\d{3})(\d{3})/g,"$1 $2 $3");
            } else {
                alert('Invalid phone number');
            }
        } else if (phone_number.match(/^02|03|07|08/)){
            if (phone_number.length === 10) {
                var formatted = phone_number.replace(/(\d{2})(\d{4})(\d{4})/g,"($1) $2 $3");
            } else {
                alert('Invalid phone number');
            }
        } else if (phone_number.length === 8){
            alert('Please use Area Code for landline numbers');
        } else {

            alert('Invalid phone number');
        }
        //update
        $("#phone").val(formatted);
    }

答案 1 :(得分:0)

您可以使用以下javascript来验证文本字段长度。

var textBox = document.getElementById("phone_no");

if(isNaN(textBox.value)){
  alert("Please inser a number as a phone number");
}
if(textBox.value.length < 8 || textBox.value.length > 10){
  alert("Enter text length between 8 to 10");
}

答案 2 :(得分:0)

您可以使用模式'\d{8}\d?\d?'\d{8}|\d{9}|\d{10}

答案 3 :(得分:0)

首先,使用pattern属性的支持不是很好(参见http://www.w3schools.com/tags/att_input_pattern.asp),所以你应该使用javascript。有关电话号码的正则表达式已在此处详细讨论过:A comprehensive regex for phone number validation

就个人而言,我建议通过将.*作为模式的答案来阅读。

答案 4 :(得分:-1)

它对我有用

pattern="[0-9]{10}"