Last active
May 30, 2017 18:47
-
-
Save r3b/ddc59d6852a9bef69ed88bd219b8c82f to your computer and use it in GitHub Desktop.
US phone number formatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function (app) { | |
"use strict"; | |
function format_nanp(num) { | |
return num | |
.replace(/[^0-9]/g, '') | |
.replace(/^\+?1?(\d{1,3})(\d{0,3})(\d{0,4})(.*)/, function replacer( | |
match, | |
p1, p2, p3, p4, offset, string) { | |
return `(${p1}) ${p2}-${p3}` + ((p4) ? ' ext. ' + p4 : ''); | |
}); | |
} | |
app.directive('formatNanp', function ($filter, $browser) { | |
return { | |
link: function ($scope, $element, $attrs) { | |
var ctrlCodes = [15, 16, 17, 18, 19, 37, 38, 39, 40, 91]; | |
function listener() { | |
$element.val(format_nanp($element.val())); | |
}; | |
$element.bind('keydown', function (event) { | |
if (ctrlCodes.indexOf(event.keyCode) === -1) { | |
$browser.defer(listener); | |
} | |
}); | |
$element.bind('change paste cut', function () { | |
$browser.defer(listener); | |
}); | |
} | |
}; | |
}); | |
})(angular.module('testApp', [])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment