Formatting phone numbers and credit cards in AngularJS

Question one (phone number for formatting):

I need to format a phone number in AngularJS, but there is no filter for it. Is there a way to use a filter or currency to format 10 digits to (555) 555-5255 ? and save the field data type as an integer?

Question two (disguising a credit card number):

I have a credit card field that displays on AngularJS, for example:

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

which returns the whole number ( 4111111111111111 ). I would like to hide it with xxx of the first 12 digits and show only the last 4. I was thinking about using a filter: the limit is for this, but I don't understand how to do it. Any ideas? Is there a way to format a number with a dash, but keep the data type as a whole? type 4111-1111-1111-1111 .

+62
angularjs number-formatting
Oct 02
source share
17 answers

In addition, if you need to format the phone number only at the output, you can use a custom filter similar to this:

 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> 
+133
04 Oct
source share

I created an AngularJS module to deal with this phonenumbers issue for myself using a custom directive and an accompanying filter.

Jsfiddle example: http://jsfiddle.net/aberke/s0xpkgmq/

Filter Usage Example: <p>{{ phonenumberValue | phonenumber }}</p> <p>{{ phonenumberValue | phonenumber }}</p>

Filter Code:

 .filter('phonenumber', function() { /* Format phonenumber as: c (xxx) xxx-xxxx or as close as possible if phonenumber length is not 10 if c is not '1' (country code not USA), does not use country code */ return function (number) { /* @param {Number | String} number - Number that will be formatted as telephone number Returns formatted number: (###) ###-#### if number.length < 4: ### else if number.length < 7: (###) ### Does not handle country codes that are not '1' (USA) */ if (!number) { return ''; } number = String(number); // Will return formattedNumber. // If phonenumber isn't longer than an area code, just show number var formattedNumber = number; // if the first character is '1', strip it out and add it back var c = (number[0] == '1') ? '1 ' : ''; number = number[0] == '1' ? number.slice(1) : number; // # (###) ###-#### as c (area) front-end 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; }; }); 

An example of using the directive:

 <phonenumber-directive placeholder="'Input phonenumber here'" model='myModel.phonenumber'></phonenumber-directive> 

Directive Code:

 .directive('phonenumberDirective', ['$filter', function($filter) { /* Intended use: <phonenumber-directive placeholder='prompt' model='someModel.phonenumber'></phonenumber-directive> Where: someModel.phonenumber: {String} value which to bind only the numeric characters [0-9] entered ie, if user enters 617-2223333, value of 6172223333 will be bound to model prompt: {String} text to keep in placeholder when no numeric input entered */ function link(scope, element, attributes) { // scope.inputValue is the value of input element used in template scope.inputValue = scope.phonenumberModel; scope.$watch('inputValue', function(value, oldValue) { value = String(value); var number = value.replace(/[^0-9]+/g, ''); scope.phonenumberModel = number; scope.inputValue = $filter('phonenumber')(number); }); } return { link: link, restrict: 'E', scope: { phonenumberPlaceholder: '=placeholder', phonenumberModel: '=model', }, // templateUrl: '/static/phonenumberModule/template.html', template: '<input ng-model="inputValue" type="tel" class="phonenumber" placeholder="{{phonenumberPlaceholder}}" title="Phonenumber (Format: (999) 9999-9999)">', }; }]) 

Full code with the module and how to use it: https://gist.github.com/aberke/042eef0f37dba1138f9e

+15
Aug 13 '14 at 3:32
source share

As shailbenq suggested, phoneformat is awesome.

Enable the phone format on your website. Create a filter for the angular module or your application.

 angular.module('ng') .filter('tel', function () { return function (phoneNumber) { if (!phoneNumber) return phoneNumber; return formatLocal('US', phoneNumber); } }); 

Then you can use the filter in your HTML.

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

If you want to use a filter in the controller.

 var number = '5553219876'; var newNumber = $filter('tel')(number); 
+13
Feb 25 '14 at 20:02
source share

enter image description here

I also found that a JQuery plugin that is easy to include in your Angular application (also with bower: D), and which checks all possible country codes with matching masks: intl-tel-input

You can then use the validationScript parameter to verify that the value entered is correct.

+11
Jul 11 '14 at 8:54
source share

Angular -ui has a directive for masking input. Perhaps this is what you want to mask (unfortunately, the documentation is not so good):

http://angular-ui.github.com/

I do not think this will help with confusing a credit card number.

+5
Oct 03 '12 at 13:01
source share

You can also check the formatting of the input mask .

This is a directive called ui-mask , and it is also part of angular-ui.utils .

It works here: Live example

At the time of this writing, there are no examples of using this directive, so I made a very simple example to demonstrate how this thing works in practice.

+5
Jan 28 '15 at 2:08
source share

This is an easy way. As the main one, I took it from http://codepen.io/rpdasilva/pen/DpbFf and made some changes. The code is easier at the moment. And you can get: in the controller - " 4124561232 ", in the field of view " (412) 456-1232 "

Filter:

 myApp.filter 'tel', -> (tel) -> if !tel return '' value = tel.toString().trim().replace(/^\+/, '') city = undefined number = undefined res = null switch value.length when 1, 2, 3 city = value else 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 res = ('(' + city + ') ' + number).trim() else res = '(' + city return res 

And the directive:

 myApp.directive 'phoneInput', ($filter, $browser) -> require: 'ngModel' scope: phone: '=ngModel' link: ($scope, $element, $attrs) -> $scope.$watch "phone", (newVal, oldVal) -> value = newVal.toString().replace(/[^0-9]/g, '').slice 0, 10 $scope.phone = value $element.val $filter('tel')(value, false) return return 
+4
Aug 28 '15 at 10:50
source share

Try using phoneformat.js ( http://www.phoneformat.com/ ), you can not only format the phone number based on user locations (en-US, ja -JP, fr-FR, de-DE, etc. ), But also checks the phone number. Its a very reliable library based on the googles libphonenumber project.

+2
Feb 01 '14 at 4:55
source share

You can use ng-pattern, which is lighter and lighter. http://tutorialzine.com/2014/12/learn-regular-expressions-in-20-minutes/ . Here you can know about it, just some meaningful words, doesnโ€™t need any directive or filter,

+1
Jul 01 '15 at 20:51
source share

I made an aberke decision and modified it to suit my taste.

  • It creates one input element.
  • It can accept extensions
  • For US numbers, it skips the country code
  • Standard Naming Conventions
  • Uses a class to use code; doesn't make up class
  • Allows you to use any other attributes allowed for the input element.

My code pen

 var myApp = angular.module('myApp', []); myApp.controller('exampleController', function exampleController($scope) { $scope.user = { profile: {HomePhone: '(719) 465-0001 x1234'}}; $scope.homePhonePrompt = "Home Phone"; }); myApp /* Intended use: <phone-number placeholder='prompt' model='someModel.phonenumber' /> Where: someModel.phonenumber: {String} value which to bind formatted or unformatted phone number prompt: {String} text to keep in placeholder when no numeric input entered */ .directive('phoneNumber', ['$filter', function ($filter) { function link(scope, element, attributes) { // scope.inputValue is the value of input element used in template scope.inputValue = scope.phoneNumberModel; scope.$watch('inputValue', function (value, oldValue) { value = String(value); var number = value.replace(/[^0-9]+/g, ''); scope.inputValue = $filter('phoneNumber')(number, scope.allowExtension); scope.phoneNumberModel = scope.inputValue; }); } return { link: link, restrict: 'E', replace: true, scope: { phoneNumberPlaceholder: '@placeholder', phoneNumberModel: '=model', allowExtension: '=extension' }, template: '<input ng-model="inputValue" type="tel" placeholder="{{phoneNumberPlaceholder}}" />' }; } ] ) /* Format phonenumber as: (aaa) ppp-nnnnxeeeee or as close as possible if phonenumber length is not 10 does not allow country code or extensions > 5 characters long */ .filter('phoneNumber', function() { return function(number, allowExtension) { /* @param {Number | String} number - Number that will be formatted as telephone number Returns formatted number: (###) ###-#### x ##### if number.length < 4: ### else if number.length < 7: (###) ### removes country codes */ if (!number) { return ''; } number = String(number); number = number.replace(/[^0-9]+/g, ''); // Will return formattedNumber. // If phonenumber isn't longer than an area code, just show number var formattedNumber = number; // if the first character is '1', strip it out var c = (number[0] == '1') ? '1 ' : ''; number = number[0] == '1' ? number.slice(1) : number; // (###) ###-#### as (areaCode) prefix-endxextension var areaCode = number.substring(0, 3); var prefix = number.substring(3, 6); var end = number.substring(6, 10); var extension = number.substring(10, 15); if (prefix) { //formattedNumber = (c + "(" + area + ") " + front); formattedNumber = ("(" + areaCode + ") " + prefix); } if (end) { formattedNumber += ("-" + end); } if (allowExtension && extension) { formattedNumber += ("x" + extension); } return formattedNumber; }; } ); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="exampleController"> <p>Phone Number Value: {{ user.profile.HomePhone || 'null' }}</p> <p>Formatted Phone Number: {{ user.profile.HomePhone | phoneNumber }}</p> <phone-number id="homePhone" class="form-control" placeholder="Home Phone" model="user.profile.HomePhone" ng-required="!(user.profile.HomePhone.length || user.profile.BusinessPhone.length || user.profile.MobilePhone.length)" /> </div> 
+1
Oct 05 '15 at 17:15
source share

I changed the code to display the phone in this format. Value: +38 (095) 411-22-23 Here you can check it enter the link description here

  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,12); }); // 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, num1, num2, num3; switch (value.length) { case 1: case 2: case 3: city = value; break; default: country = value.slice(0, 2); city = value.slice(2, 5); num1 = value.slice(5,8); num2 = value.slice(8,10); num3 = value.slice(10,12); } if(country && city && num1 && num2 && num3){ return ("+" + country+" (" + city + ") " + num1 +"-" + num2 + "-" + num3).trim(); } else if(country && city && num1 && num2) { return ("+" + country+" (" + city + ") " + num1 +"-" + num2).trim(); }else if(country && city && num1) { return ("+" + country+" (" + city + ") " + num1).trim(); }else if(country && city) { return ("+" + country+" (" + city ).trim(); }else if(country ) { return ("+" + country).trim(); } }; }); 
+1
Jan 14 '16 at 14:02
source share

You will need to create your own form controls (as directives) for the phone number and credit card. See โ€œImplementing a custom form control (using ngModel)โ€ on the forms page.

As Narretz already mentioned, the Angular -ui Mask directive should help you get started.

0
Oct 03
source share

A simple filter is something like this (use a number class to filter the end of the input filter in []):

 <script type="text/javascript"> // Only allow number input $('.numeric').keyup(function () { this.value = this.value.replace(/[^0-9+-\.\,\;\:\s()]/g, ''); // this is filter for telefon number !!! }); 

0
Nov 05 '15 at 12:35
source share

This is how I created the ssn directive that validates the template, and I used RobinHerbots jquery.inputmask

 angular.module('SocialSecurityNumberDirective', []) .directive('socialSecurityNumber', socialSecurityNumber); function socialSecurityNumber() { var jquery = require('jquery'); var inputmask = require("jquery.inputmask"); return { require: 'ngModel', restrict: 'A', priority: 1000, link: function(scope,element, attr, ctrl) { var jquery_element = jquery(element); jquery_element.inputmask({mask:"***-**-****",autoUnmask:true}); jquery_element.on('keyup paste focus blur', function() { var val = element.val(); ctrl.$setViewValue(val); ctrl.$render(); }); var pattern = /^\d{9}$/; var newValue = null; ctrl.$validators.ssnDigits = function(value) { newValue = element.val(); return newValue === '' ? true : pattern.test(newValue); }; } }; } 
0
Jan 19 '16 at 19:09
source share

I solved this problem with a custom Angular filter, but mine takes advantage of regex capture groups, and therefore the code is really short. I connect it to a separate stripNonNumeric filter to sanitize input:

 app.filter('stripNonNumeric', function() { return function(input) { return (input == null) ? null : input.toString().replace(/\D/g, ''); } }); 

The phoneFormat filter correctly formats a phone number with or without a city code. (I do not need international number support.)

 app.filter('phoneFormat', function() { //this establishes 3 capture groups: the first has 3 digits, the second has 3 digits, the third has 4 digits. Strings which are not 7 or 10 digits numeric will fail. var phoneFormat = /^(\d{3})?(\d{3})(\d{4})$/; return function(input) { var parsed = phoneFormat.exec(input); //if input isn't either 7 or 10 characters numeric, just return input return (!parsed) ? input : ((parsed[1]) ? '(' + parsed[1] + ') ' : '') + parsed[2] + '-' + parsed[3]; } }); 

Use them simply:

 <p>{{customer.phone | stripNonNumeric | phoneFormat}}</p> 

The regular expression for the stripNonNumeric filter comes from here .

0
Jul 13 '16 at 17:10
source share

Find Plunker to format credit card numbers using the angularjs directive. Format card numbers in xxxxxxxxxxxx3456 Fromat.

 angular.module('myApp', []) .directive('maskInput', function() { return { require: "ngModel", restrict: "AE", scope: { ngModel: '=', }, link: function(scope, elem, attrs) { var orig = scope.ngModel; var edited = orig; scope.ngModel = edited.slice(4).replace(/\d/g, 'x') + edited.slice(-4); elem.bind("blur", function() { var temp; orig = elem.val(); temp = elem.val(); elem.val(temp.slice(4).replace(/\d/g, 'x') + temp.slice(-4)); }); elem.bind("focus", function() { elem.val(orig); }); } }; }) .controller('myCtrl', ['$scope', '$interval', function($scope, $interval) { $scope.creditCardNumber = "1234567890123456"; }]); 
0
Sep 23 '16 at 8:58
source share

Insert the "xeditable" module into your angular application (freely available):

var App = angular.module('App', ['xeditable']);

And then use the inline function in your HTML as follows:

<div>{{ value|number:2 }}</div>

0
Aug 31 '17 at 6:20
source share



All Articles