jQuery验证澳大利亚电话号码

时间:2015-05-04 07:37:41

标签: javascript jquery regex validation formatting

我正在尝试从输入框中获取值,验证&格式化数字,然后更新输入字段。

我希望它验证所有澳大利亚电话号码(手机和固定电话) 格式化手机号码 04XX XXX XXX 和固定电话号码 (0X)XXXX XXXX

var phone_number = $("#phone").val();
//validate mobile number
var formatted = phone_number.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
//replace number
$("#phone").val(formatted);

任何帮助都很棒:)

3 个答案:

答案 0 :(得分:3)

您可以使用您建议的相同正则表达式/替换逻辑。

的HTML

Mobile:<input id = "mobile" type = "tel" maxlength=8></input>
Landline:<input id = "landline" type = "tel" maxlength=10></input>

的jquery

$("#mobile").blur(function(){
    var mobile_ele = $("#mobile");
    var mobileNum = mobile_ele.val();
    var formattedNum = mobileNum.replace(/(\d{2})(\d{3})(\d{3})/g,"04$1 $2 $3");
    mobile_ele.val(formattedNum);
});
$("#landline").blur(function(){
    var landline_ele = $("#landline");
    var landlineNum = mobile_ele.val();
    var formattedNum = landlineNum.replace(/(\d{2})(\d{4})(\d{4})/g,"($1) $2 $3");
    mobile_ele.val(formattedNum);
});

演示:https://jsfiddle.net/7c0d418t/

答案 1 :(得分:3)

我想出了一个解决方案,不确定它是多么优化,但有人可能想详细说明。

    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);
    }

DEMO:https://jsfiddle.net/kb4u536a/

答案 2 :(得分:1)

您可以在此处找到200多个国家/地区的电话验证码:https://github.com/googlei18n/libphonenumber