Auto Format Phone Number Input Field Angular

Auto Format Phone Number Input Field Angular
Project: Angular phone number filtering on input
Author: Philip Da Silva
Edit Online: View on CodePen
License: MIT

This code snippet showcases an automatic phone number formatting feature implemented using AngularJS directives and filters. By simply applying the “phoneInput” directive to your input fields, you can enable automatic formatting of phone numbers as users type. The directive intelligently removes non-numeric characters and applies the appropriate formatting, including parentheses around the city code and a hyphen between the first three digits and the remaining digits of the phone number.

This not only saves your users from the hassle of formatting phone numbers correctly but also ensures a consistent and visually appealing display. Say goodbye to manual formatting and give your users a seamless experience with this handy AngularJS solution.

How to Create Auto Format Phone Number Input Field Angular

First of all, load the Normalize CSS by adding the following CDN link into the head tag of your HTML document. (Optional)

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

Create the “phoneInput” directive in your AngularJS application. This directive will handle the automatic phone number formatting.

<div class="body" ng-app="myApp">
    <div class="wrapper" ng-controller="MyCtrl">
        <div class="info">Raw Value: {{phoneVal}}</div>
        <div class="info">Filtered Value: {{phoneVal | tel}}</div>

        <input class="input-phone" type='text' phone-input ng-model="phoneVal"/>
    </div>
</div>

The CSS styles are optional, you can style the phone number input according to your needs.

body, html, .body {
  height: 100%;
  width: 100%;
}

.cd__main {
  background: radial-gradient(closest-corner, rgba(16, 47, 70, 0) 60%, rgba(16, 47, 70, 0.26)), linear-gradient(108deg, #26D0CE, #1A2980 90%) !important;
}

.body {
  display: table;
}

.wrapper {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

.info {
  margin: 0.5em 0;
  font-size: 1.25em;
  color: #FFF;
  text-shadow: 0 0 0.5em #000;
}

.input-phone {
  display: block;
  margin: 2em auto;
  padding: 0.5em 0.25em;
  border: none;
  border-radius: 0.2em;
  font-size: 1.5em;
  text-align: center;
  box-shadow: 0 0 1em 0.25em rgba(0, 0, 0, 0.2);
}

Load the AngularJS by adding the following CDN link before closing the body tag:

<script src='//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js'></script>

Finally, add the following JavaScript function to enable auto-formatting phone numbers:

/*
Automatic phone number formatting in input field

Credits:
    - Wade Tandy via
    http://stackoverflow.com/questions/19094150/using-angularjs-directive-to-format-input-field-while-leaving-scope-variable-unc
    
    - kstep via
    http://stackoverflow.com/questions/12700145/how-to-format-a-telephone-number-in-angularjs
    
    - hans via
    https://codepen.io/hans/details/uDmzf/
*/

var myApp = angular.module('myApp', []);
 
myApp.controller('MyCtrl', function($scope) {
  $scope.currencyVal;
});

myApp.directive('phoneInput', function($filter, $browser) {
    return {
        require: 'ngModel',
        link: function($scope, $element, $attrs, ngModelCtrl) {
            var listener = function() {
                var value = $element.val().replace(/[^0-9]/g, '');
                $element.val($filter('tel')(value, false));
            };

            // This runs when we update the text field
            ngModelCtrl.$parsers.push(function(viewValue) {
                return viewValue.replace(/[^0-9]/g, '').slice(0,10);
            });

            // This runs when the model gets updated on the scope directly and keeps our view in sync
            ngModelCtrl.$render = function() {
                $element.val($filter('tel')(ngModelCtrl.$viewValue, false));
            };

            $element.bind('change', listener);
            $element.bind('keydown', function(event) {
                var key = event.keyCode;
                // If the keys include the CTRL, SHIFT, ALT, or META keys, or the arrow keys, do nothing.
                // This lets us support copy and paste too
                if (key == 91 || (15 < key && key < 19) || (37 <= key && key <= 40)){
                    return;
                }
                $browser.defer(listener); // Have to do this or changes don't get picked up properly
            });

            $element.bind('paste cut', function() {
                $browser.defer(listener);
            });
        }

    };
});
myApp.filter('tel', function () {
    return function (tel) {
        console.log(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 1:
            case 2:
            case 3:
                city = value;
                break;

            default:
                city = value.slice(0, 3);
                number = value.slice(3);
        }

        if(number){
            if(number.length>3){
                number = number.slice(0, 3) + '-' + number.slice(3,7);
            }
            else{
                number = number;
            }

            return ("(" + city + ") " + number).trim();
        }
        else{
            return "(" + city;
        }

    };
});

That’s all! hopefully, you have successfully created an auto format phone number input field in Angular. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply