最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to format a USCAN phone number using jQuery as you type? - Stack Overflow

programmeradmin3浏览0评论

I have a phone field in an HTML form that needs to be formatted

(555) 555-5555

Here's the field:

<input type="tel" id="phone" name="phone" placeholder="(555) 555-5555" autoplete="off" maxlength="14" required="required">

A few requirements:

  1. It should auto-format as you type.
  2. It should auto-format after pasting.
  3. It should only allow digits, (, ), -, and spaces to be entered.
  4. If the user types one of the non-digit characters that are part of the mask, it should allow those characters in the field so long as they're in the right position. Don't strip them. For example, if the first character they type into the field is an open parentheses, it should allow it. If it's a digit, it should update it to an open parentheses followed by that digit. If it's any other character, it should remove it.

How can this type-as-you-go mask be applied with these requirements using jQuery/Javascript?

I have a phone field in an HTML form that needs to be formatted

(555) 555-5555

Here's the field:

<input type="tel" id="phone" name="phone" placeholder="(555) 555-5555" autoplete="off" maxlength="14" required="required">

A few requirements:

  1. It should auto-format as you type.
  2. It should auto-format after pasting.
  3. It should only allow digits, (, ), -, and spaces to be entered.
  4. If the user types one of the non-digit characters that are part of the mask, it should allow those characters in the field so long as they're in the right position. Don't strip them. For example, if the first character they type into the field is an open parentheses, it should allow it. If it's a digit, it should update it to an open parentheses followed by that digit. If it's any other character, it should remove it.

How can this type-as-you-go mask be applied with these requirements using jQuery/Javascript?

Share Improve this question asked Feb 18, 2015 at 16:01 Nick PetrieNick Petrie 5,60811 gold badges44 silver badges52 bronze badges 2
  • 1 There are a plethora of input masking plugins, try this one for example: igorescobar.github.io/jQuery-Mask-Plugin – Rory McCrossan Commented Feb 18, 2015 at 16:02
  • Thanks @RoryMcCrossan. You're right. I had reviewed a couple masking plugins. But, even if I could find one that meets all my requirements, it would've added unnecessary overhead unless I went in and removed the features I didn't need. So, I opted to write something just for the phone mask. – Nick Petrie Commented Feb 18, 2015 at 16:21
Add a ment  | 

3 Answers 3

Reset to default 7

I pieced together answers to other related questions, as well as my own code, and came up with this solution that seems to work well:

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

I like Nick Petrie's answer a lot, but I think the closing parenthesis ")" should be added when the number in position 3 is entered, not the number in position 4 (as it currently does).

Here's a modified version:

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

    }
});

I've changed else if(i==3) newval+=numbers[i]+") "; to else if(i==2) newval+=numbers[i]+") "; and added an if(event.which != 8){} statement to catch backspace key entry (as it would otherwise get stuck).

You can also use this small method for this:

$("#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();
    }
});
发布评论

评论列表(0)

  1. 暂无评论