2

I found the following code for formatting the phone number in JavaScript on this post from stack overflow but it is not in U.S standard format and I want the space after closing ')'

i.e. The following code gave me output (123)456-7890 but I want (123) 456-7890, want to include space after the closing ')'. I tried it but no luck.

<script type="text/javascript">
    //Phone validation
    var zChar = new Array(' ', '(', ')', '-', '.');
    var maxphonelength = 13;
    var phonevalue1;
    var phonevalue2;
    var cursorposition;

    function ParseForNumber1(object) {
        phonevalue1 = ParseChar(object.value, zChar);
    }
    function ParseForNumber2(object) {
        phonevalue2 = ParseChar(object.value, zChar);
    }

    function backspacerUP(object, e) {
        if (e) {
            e = e
        } else {
            e = window.event
        }
        if (e.which) {
            var keycode = e.which
        } else {
            var keycode = e.keyCode
        }

        ParseForNumber1(object)

        if (keycode >= 48) {
            ValidatePhone(object)
        }
    }

    function backspacerDOWN(object, e) {
        if (e) {
            e = e
        } else {
            e = window.event
        }
        if (e.which) {
            var keycode = e.which
        } else {
            var keycode = e.keyCode
        }
        ParseForNumber2(object)
    }

    function GetCursorPosition() {

        var t1 = phonevalue1;
        var t2 = phonevalue2;
        var bool = false
        for (i = 0; i < t1.length; i++) {
            if (t1.substring(i, 1) != t2.substring(i, 1)) {
                if (!bool) {
                    cursorposition = i
                    bool = true
                }
            }
        }
    }

    function ValidatePhone(object) {

        var p = phonevalue1

        p = p.replace(/[^\d]*/gi, "")

        if (p.length < 3) {
            object.value = p
        } else if (p.length == 3) {
            pp = p;
            d4 = p.indexOf('(')
            d5 = p.indexOf(')')
            if (d4 == -1) {
                pp = "(" + pp;
            }
            if (d5 == -1) {
                pp = pp + ")";
            }
            object.value = pp;
        } else if (p.length > 3 && p.length < 7) {
            p = "(" + p;
            l30 = p.length;
            p30 = p.substring(0, 4);
            p30 = p30 + ")"

            p31 = p.substring(4, l30);
            pp = p30 + p31;

            object.value = pp;

        } else if (p.length >= 7) {
            p = "(" + p;
            l30 = p.length;
            p30 = p.substring(0, 4);
            p30 = p30 + ")"

            p31 = p.substring(4, l30);
            pp = p30 + p31;

            l40 = pp.length;
            p40 = pp.substring(0, 8);
            p40 = p40 + "-"

            p41 = pp.substring(8, l40);
            ppp = p40 + p41;

            object.value = ppp.substring(0, maxphonelength);
        }

        GetCursorPosition()

        if (cursorposition >= 0) {
            if (cursorposition == 0) {
                cursorposition = 2
            } else if (cursorposition <= 2) {
                cursorposition = cursorposition + 1
            } else if (cursorposition <= 5) {
                cursorposition = cursorposition + 2
            } else if (cursorposition == 6) {
                cursorposition = cursorposition + 2
            } else if (cursorposition == 7) {
                cursorposition = cursorposition + 4
                e1 = object.value.indexOf(')')
                e2 = object.value.indexOf('-')
                if (e1 > -1 && e2 > -1) {
                    if (e2 - e1 == 4) {
                        cursorposition = cursorposition - 1
                    }
                }
            } else if (cursorposition < 11) {
                cursorposition = cursorposition + 3
            } else if (cursorposition == 11) {
                cursorposition = cursorposition + 1
            } else if (cursorposition >= 12) {
                cursorposition = cursorposition
            }

            var txtRange = object.createTextRange();
            txtRange.moveStart("character", cursorposition);
            txtRange.moveEnd("character", cursorposition - object.value.length);
            txtRange.select();
        }

    }

    function ParseChar(sStr, sChar) {
        if (sChar.length == null) {
            zChar = new Array(sChar);
        }
        else zChar = sChar;

        for (i = 0; i < zChar.length; i++) {
            sNewStr = "";

            var iStart = 0;
            var iEnd = sStr.indexOf(sChar[i]);

            while (iEnd != -1) {
                sNewStr += sStr.substring(iStart, iEnd);
                iStart = iEnd + 1;
                iEnd = sStr.indexOf(sChar[i], iStart);
            }
            sNewStr += sStr.substring(sStr.lastIndexOf(sChar[i]) + 1, sStr.length);

            sStr = sNewStr;
        }

        return sNewStr;
    }
</script>

I am trying to use this function in multiple phone textboxes and all those are in asp:Textbox.

  • 1
    Array(' ', '(', ') ', '-', '.'); – Jonas Wilms Aug 03 '17 at 17:20
  • 1
    That code seems really complicated. – epascarello Aug 03 '17 at 17:28
  • Possible duplicate of [How to format a phone number with jQuery](https://stackoverflow.com/questions/8760070/how-to-format-a-phone-number-with-jquery) – Heretic Monkey Aug 03 '17 at 18:44
  • Your code is very complicated and I don't quite get understand what you really want. Assuming to got a string of number like `var phone = "1234567890"` or `var phone = "123-456-7890"` and you want it to be formatted as `(ddd) ddd-dddd` this would work `phone.replace(/\D/g,"").replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3")` It will first strip all non digit, then replace the 10 digit string number with your preferred format – tkhuynh Aug 03 '17 at 18:56

4 Answers4

0

In my opinion the code is overly complicated. You should provide a number only input ( and may + too), and then show the result below the input, so the user sees what it is formatted to. Html:

<input type="number" id="phone">
<p id="showphone">enter a number above</p>

And the js:

window.addEventListener("load",function(){
  var phone = document.getElementById("phone");
  var showphone = document.getElementById("showphone");

 phone.oninput = function(){
  var result = phone.value.split("");
  result.splice(0,0,"(")
  result.splice(4,0,") ")
  result.splice(8,0," - ");

  showphone.textContent = result.join("");
 };
});

In action

If you want to display these formattings just if neccessary, do:

if(result.length > 3 ) result.splice(4,0,"(")
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • I am using the above code in asp:Textbox. Is your solution will work for asp control?? –  Aug 03 '17 at 17:34
  • Though I deleted the phone number the label still shows "() - " how do you delete that –  Aug 07 '17 at 18:32
0

Here is a function to do that

function formatPhone(__phone){      
    var pt = /[\(\)\- ]+/gi
    __phone = __phone.replace(pt, '');
    __phone = '('+__phone.substr(0,3)+') '+__phone.substr(2,3)+'-'+__phone.substr(6,4);
    return __phone;
}
Eric
  • 9,870
  • 14
  • 66
  • 102
  • Are you asking me why I named the variable holding a phone number in string "__phone" ????????? – Eric Aug 03 '17 at 18:51
  • Yes. why not phone?? the op may wants to edit the code, the __ makes it more hard – Jonas Wilms Aug 04 '17 at 05:49
  • Oh well I like to add __ in front of params so it makes it clear in my code what is passed. – Eric Aug 04 '17 at 13:08
  • its rather usual to use underscores for unused parameters and private proerties / methods. And im not shure how it should help you coding if you now that its a parameter... – Jonas Wilms Aug 04 '17 at 13:50
0

To insert the space after the closing braces ')' use the following trick:

function markSpace(field) {
        if (field.value.includes(")")) {
            field.value = field.value.split(')').join(') ');
        }
        if (field.value.includes(") ")) {
            field.value = field.value.replace(/  +/g, ' ');

        }
    }

and call the above function as onblur="markSpace(this);"

Or, this will be short and working answer for your problem

JavaScript code:

 window.addFormat = function addFormat(f) {
        var r = /(\D+)/g,
            npa = '',
            nxx = '',
            last4 = '';
        f.value = f.value.replace(r, '');
        npa = f.value.substr(0, 3);
        nxx = f.value.substr(3, 3);
        last4 = f.value.substr(6, 4);
        f.value = '(' + npa + ') ' + nxx + '-' + last4;
    }

and asp:Textbox as

<asp:TextBox MaxLength="14" 
             runat="server" 
             ID="txtPhone"  
             placeholder="(xxx) xxx-xxxx" 
             onKeyup='addFormat(this)'/>

Reference: This Stack Overflow post

Raj Baral
  • 661
  • 6
  • 19
0

You may have some clues out of here.

let testNumber = "(123-12)3-1234";

function formatPhoneNumber(num) {
  const number = num.match(/\d/g, "");
  const joinedNumber = number.join("");
  console.log(joinedNumber);
  const regex = /^(\d{3})(\d{3})(\d{4})$/;
  const final = joinedNumber.replace(regex, "($1)$2-$3");
  return final;
  console.log(final);
}
formatPhoneNumber(testNumber);
// print on console: (123)123-1234

I put console.logs so that you can visualize what is going on.
0. the format of testNumber doesn't matter, but it needs to be 10 digits (because of const regex)
1. const number returns an array with each number as an element.
2. const joinedNumber returns a number that all elements are attached (1231231234)
3. const regex makes parts so that you can control later with replace// () = parts, so as you can see there are 3 parts. You can change regex format as you want to format
4. finally, joinedNumber.replace(regex, "($1)$2-$3) will return (123)123-1234
5. you can change "($1)$2-$3 part to make a format whatever you want.

Hope you find it helpful.

brandonwie
  • 551
  • 5
  • 12