如何在键入时使用jQuery格式化US/CAN电话号码?

Nic*_*rie 1 javascript regex jquery phone-number

我在HTML表单中有一个需要格式化的电话字段

(555)555-5555

这是领域:

<input type="tel" id="phone" name="phone" placeholder="(555) 555-5555" autocomplete="off" maxlength="14" required="required">
Run Code Online (Sandbox Code Playgroud)

一些要求:

  1. 它应该在您键入时自动格式化.
  2. 它应该在粘贴后自动格式化.
  3. 它应该只允许输入数字,(,), - 和空格.
  4. 如果用户键入作为掩码一部分的非数字字符之一,则只要它们位于正确的位置,它就应该允许字段中的那些字符.不要剥掉它们.例如,如果他们在字段中键入的第一个字符是开括号,则应该允许它.如果它是一个数字,它应该将它更新为一个开括号后跟该数字.如果它是任何其他角色,它应该删除它.

如何使用jQuery/Javascript将这种类型的需求应用于这些需求?

Nic*_*rie 6

我拼凑了其他相关问题的答案,以及我自己的代码,并提出了似乎运行良好的解决方案:

// 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));
});
Run Code Online (Sandbox Code Playgroud)