How to format a phone number on the fly
March 24th, 2010
This example show you how to format a phone number in the text input while typing on the fly. It also stores an unformatted value of the number in a variable.
Try it out.
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" backgroundColor="#FFFFFF" width="300" height="200"> <mx:Script> <![CDATA[ include "/as/phoneformat.as"; ]]> </mx:Script> <mx:PhoneFormatter id="usPhone" formatString="(###) ###-####" validPatternChars="#-() "/> <mx:TextInput x="91.5" y="89" id="_phone" change="setPhone();" width="110" restrict="0-9"/> <mx:Label x="48.5" y="91" text="Phone"/> <mx:Button x="146.5" y="119" label="Clear" click="_phone.text = '';"/> </mx:Application>
// ActionScript file [Bindable] public var phone:String = ""; private function setPhone():void { var area:String; var prefix:String; var phonenumber:String;; //when the numbers in length you type is equal // to 3 then format areacode. if(_phone.length == 3){ _phone.text = "(" + _phone.text + ") " _phone.setSelection(6,6); } //add dash to text field and set the cursor if (_phone.length == 9){ _phone.text = _phone.text + "-"; _phone.setSelection(10,10); _phone.maxChars = 14; } // now finally get the number only with no format to save to the DB and // reformat the phone incase formatting misses. //This is mainly for users that just type a bunch of numnbers really fast, // it will still format the number if(_phone.length == 14){ area = _phone.text.slice(1,4); prefix = _phone.text.slice(6,9); phonenumber = _phone.text.slice(10,14); phone = area + prefix + phonenumber; _phone.text = usPhone.format(phone); } }