Advertisements
Home > AngularJs > Formatting phone number with AngularJS

Formatting phone number with AngularJS


——————————————————————–

Javascript

angular.module(‘ng’).filter(‘tel’, function () {
return function (tel) {
if (!tel) { return ”; }

var value = tel.toString().trim().replace(/^\+/, ”);

if (value.match(/[^0-9]/)) {
return tel;
}

var country, city, number;

switch (value.length) {
case 10: // +1PPP####### -> C (PPP) ###-####
country = 1;
city = value.slice(0, 3);
number = value.slice(3);
break;

case 11: // +CPPP####### -> CCC (PP) ###-####
country = value[0];
city = value.slice(1, 4);
number = value.slice(4);
break;

case 12: // +CCCPP####### -> CCC (PP) ###-####
country = value.slice(0, 3);
city = value.slice(3, 5);
number = value.slice(5);
break;

default:
return tel;
}

if (country == 1) {
country = “”;
}

number = number.slice(0, 3) + ‘-‘ + number.slice(3);

return (country + ” (” + city + “) ” + number).trim();
};
});

———————————————————————

HTML

<div ng-app>

<div ng-controller=”Ctrl”>

<label>Enter a telephone number to format:</label>
<input ng-model=”phoneNumber” ng-bind=”phoneNumber | tel” /><br><br>
Result formatted: {{ phoneNumber | tel }}
</div>
</div>

——————————————————————-

http://jsfiddle.net/rahuladmin/0ff1v2kr/

Advertisements
Categories: AngularJs
  1. July 26, 2015 at 8:23 pm

    Reblogged this on Dinesh Ram Kali..

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: