使用jQuery实时输入格式化美国/加拿大电话号码的方法是什么?

3
我在一个HTML表单中有一个电话号码字段,需要进行格式化。
(555) 555-5555
以下是该字段:
<input type="tel" id="phone" name="phone" placeholder="(555) 555-5555" autocomplete="off" maxlength="14" required="required">

一些要求:
  1. 输入时应自动格式化。
  2. 粘贴后应自动格式化。
  3. 只允许输入数字、()、- 和空格。
  4. 如果用户输入掩码中的非数字字符,则只要它们在正确的位置上,就应允许这些字符存在于字段中。不要删除它们。例如,如果他们在字段中输入的第一个字符是开放括号,则应允许它。如果是数字,它应更新为后跟该数字的开放括号。如果是任何其他字符,则应将其删除。
如何使用 jQuery/Javascript 实现这种实时掩码并满足这些要求?

1
有大量的输入掩码插件可供选择,例如可以尝试使用这个:http://igorescobar.github.io/jQuery-Mask-Plugin/ - Rory McCrossan
感谢 @RoryMcCrossan。你说得对。我已经审查了几个掩码插件。但是,即使我能找到一个符合我所有要求的插件,除非我去除不需要的功能,否则它都会增加不必要的开销。因此,我选择编写一些仅用于电话掩码的东西。 - Nick Petrie
3个回答

7
我整合了其他相关问题的答案以及自己的代码,得出了这个看起来很有效的解决方案:
// Phone formatting: (555) 555-5555
$("#phone").on("keyup paste", function() {
    // Remove invalid chars from the input
    var input = this.value.replace(/[^0-9\(\)\s\-]/g, "");
    var inputlen = input.length;
    // Get just the numbers in the input
    var numbers = this.value.replace(/\D/g,'');
    var numberslen = numbers.length;
    // Value to store the masked input
    var newval = "";

    // Loop through the existing numbers and apply the mask
    for(var i=0;i<numberslen;i++){
        if(i==0) newval="("+numbers[i];
        else if(i==3) newval+=") "+numbers[i];
        else if(i==6) newval+="-"+numbers[i];
        else newval+=numbers[i];
    }

    // Re-add the non-digit characters to the end of the input that the user entered and that match the mask.
    if(inputlen>=1&&numberslen==0&&input[0]=="(") newval="(";
    else if(inputlen>=6&&numberslen==3&&input[4]==")"&&input[5]==" ") newval+=") ";
    else if(inputlen>=5&&numberslen==3&&input[4]==")") newval+=")";
    else if(inputlen>=6&&numberslen==3&&input[5]==" ") newval+=" ";
    else if(inputlen>=10&&numberslen==6&&input[9]=="-") newval+="-";

    $(this).val(newval.substring(0,14));
});

有没有办法让这个看起来更漂亮,并在输入前三个数字后立即显示最后一个括号“)”?我觉得用户在输入区号后会停顿一下,而且只有第一个括号看起来很奇怪。 - Jonathan Safa

2

我非常喜欢Nick Petrie的答案,但是我认为应该在输入第3位数字时添加右括号“)”,而不是第4位数字(目前是这样做的)。

以下是修改后的版本:

// Phone formatting: (555) 555-5555
$("#Phone").on("keyup paste", function(event) {

    // Don't run for backspace key entry, otherwise it bugs out
    if(event.which != 8){

        // Remove invalid chars from the input
        var input = this.value.replace(/[^0-9\(\)\s\-]/g, "");
        var inputlen = input.length;
        // Get just the numbers in the input
        var numbers = this.value.replace(/\D/g,'');
        var numberslen = numbers.length;
        // Value to store the masked input
        var newval = "";

        // Loop through the existing numbers and apply the mask
        for(var i=0;i<numberslen;i++){
            if(i==0) newval="("+numbers[i];
            else if(i==2) newval+=numbers[i]+") ";
            else if(i==6) newval+="-"+numbers[i];
            else newval+=numbers[i];
        }

        // Re-add the non-digit characters to the end of the input that the user entered and that match the mask.
        if(inputlen>=1&&numberslen==0&&input[0]=="(") newval="(";
        else if(inputlen>=6&&numberslen==3&&input[4]==")"&&input[5]==" ") newval+=") ";
        else if(inputlen>=5&&numberslen==3&&input[4]==")") newval+=" ";
        else if(inputlen>=6&&numberslen==3&&input[5]==" ") newval+=" ";
        else if(inputlen>=10&&numberslen==6&&input[9]=="-") newval+="-";

        $(this).val(newval.substring(0,14));

    }
});

我将else if(i==3) newval+=numbers[i]+") ";更改为else if(i==2) newval+=numbers[i]+") ";,并添加了一个if(event.which != 8){}语句来捕获退格键输入(否则会卡住)。


0

你也可以使用这个小方法:

$("#phone").keydown(function(e) {
    var curchr = this.value.length;
    var curval = $(this).val();
    if (curchr == 3) {
        if( e.keyCode!=8 ){
            $(this).val("(" + curval + ")" + " ");
        }
    } else if (curchr == 9) {
        if( e.keyCode!=8 ){
            $(this).val(curval + "-");
        }
    }
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105) && e.keyCode !=8 ) {
        e.preventDefault();
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接