How to auto-format phone numbers and mask telephone numbers using Javascript
You can use the sample javascript given in this tutorial for javascript phone format and auto format telephone numbers during phone number entery into a phone textbox or mask textboxes for telephone numbers.
The sample javascript phone format code is prepared to format US phone number formats.
This phone format is same as Turkish telephone number format.
The phone number format in this article that the javascript can be used to mask is like (222)336-4520
You can freely use this javascript phone formatting script code.
You can enter phone number below in the textbox and you will see the telephone number entered will be formatted automatically.
<!-- This script is based on the javascript code of Roman Feldblum (web.developer@programmer.net) --> <!-- Original script : http://javascript.internet.com/forms/format-phone-number.html --> <!-- Original script is revised by Eralper Yilmaz (http://www.eralper.com) --> <!-- Revised script : http://www.kodyaz.com -->
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 } } } }