Click here to Skip to main content
14,970,493 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Hi all,

I need to mask a phone number in the following format :

(XXX)-XX-XXXXXXX

eg:(971)-05-8907645

here the first 3 numbers ie within bracket (971) should be constant and cannot be editable.User have to enter the remaining numbers.Can anyone help me please.Thanks in advance.

What I have tried:

<asp:TextBox ID="txt_mobile" TabIndex="6"  runat="server"  Width="200px" CssClass="textboxAll" ></asp:TextBox>
                                            <asp:MaskedEditExtender ID="MaskedEditExtender1" runat="server" TargetControlID="txt_mobile" Mask="(999)999-9999" ClearMaskOnLostFocus="false"></asp:MaskedEditExtender>
Posted
Updated 30-Dec-17 18:47pm

1 solution

This can be achieved through javascript validation.please see the below function
JavaScript
HTMLInputElement.prototype.maskPhoneNumber = function maskPhoneNumber(readOnlyStart, readOnlyEnd) {

           this.addEventListener('keydown', function (event) {
               var which = event.which;
               if (((which == 8) && (this.selectionStart <= readOnlyEnd && this.selectionStart >= readOnlyStart)) ||
                 ((which == 46) && (this.selectionStart < readOnlyEnd))) {
                   event.preventDefault();

               }


           });
           this.addEventListener('keypress', function (event) {
               var which = event.which;
               if ((event.which != 0) && (this.selectionStart < readOnlyEnd && this.selectionStart > readOnlyStart)) {
                    event.preventDefault();

               }
           });
       }


and call the function

JavaScript
document.getElementById("txt_mobile").maskPhoneNumber(0, 6);


html

HTML
<input type="text" id="txt_mobile" value="(971)-"  />
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900