Format telephone and credit card numbers in AngularJS

J Castillo picture J Castillo · Oct 3, 2012 · Viewed 131.5k times · Source

Question one (formatting telephone number):

I'm having to format a telephone number in AngularJS but there is no filter for it. Is there a way to use filter or currency to format 10 digits to (555) 555-5255? and still preserve the data type of the field as integer?

Question two (masking credit card number):

I have a credit card field that is mapped to AngularJS, like:

<input type="text" ng-model="customer.creditCardNumber"> 

which is returning the whole number (4111111111111111). I will like to mask it with xxx the first 12 digits and only show the last 4. I was thinking on using filter: limit for this but am not clear as how. Any ideas? Is there a way to also format the number with dashes but still retain the data type as integer? sort of 4111-1111-1111-1111.

Answer

kstep picture kstep · Oct 4, 2012

Also, if you need to format telephone number on output only, you can use a custom filter like this one:

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();
    };
});

Then you can use this filter in your template:

{{ phoneNumber | tel }}
<span ng-bind="phoneNumber | tel"></span>