Rob Allred

Developer, Outdoor Enthusiast & Purveyor of Odd Things. AngularJS, Javascript, ASP_NET, OrchardCMS.

  • Twitter

Filter Phone Number in Angular

Posted on August 16, 2016

AngularLogoI have been meaning to store filters I find useful and write a little blog post about each one just so I have access to them and maybe someone else will find them handy. This filter is for displaying phone numbers in the following format: 1(xxx) xxx-xxxx

When users are inputting their information you can get all kinds of junk and formats. Instead of forcing the users to a rigid validation format, I just strip out all the non-numeric values and store the raw numbers. Then on the client side code I use this filter to display the phone number in a nice format.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    App.filter('phoneNumber', function () {
        return function (number) {
            if (!number) { return ''; }
            number = String(number);
            number = number.replace(/[^0-9]*/g, '');
            var formattedNumber = number;
 
            var c = (number[0] == '1') ? '1' : '';
            number = number[0] == '1' ? number.slice(1) : number;
 
            var area = number.substring(0, 3);
            var front = number.substring(3, 6);
            var end = number.substring(6, 10);
 
            if (front) {
                formattedNumber = (c + "(" + area + ") " + front);
            }
            if (end) {
                formattedNumber += ("-" + end);
            }
            return formattedNumber;
        };
    });
 
 
 
//using the code would look something like the following
   <div>{{User.PhoneNumber|phoneNumber}}</div>

Filed Under: anjularjs, javascript Tagged With: angular filters, angularjs, Code Snippets, javascript

Categories

  • Accessibility (1)
  • anjularjs (5)
  • Asp.Net (3)
  • CSharp (2)
  • CSS (1)
  • Database (3)
  • Github (1)
  • Html5 (1)
  • javascript (11)
  • Linq (1)
  • Orchard Cms (9)
  • Regex (1)
  • SQL (1)
  • Uncategorized (1)
  • Videos (4)
  • vuejs (1)
  • Web Api (2)

Recent Posts

  • Commonly used regex for zip codes and addresses
  • Delete all the tables from your database
  • Orchard CMS Content Control Wrapper
  • Orchard Harvest 2017
  • Sending Emails in a Asp.net WebApi

Copyright © 2014