JSFiddle - React, Tailwind, and code Playground
by Annie Lagang
HTML
<div ng-app="demoApp">
<input type="text" id="phonenumber" phone-input ng-model="USPhone" >
<p>{{USPhone | tel}}</p>
</div>
JavaScript
// SOURCE: https://stackoverflow.com/a/35174052/906815
/* Rules:
1. Restrict input in these fields to numerical characters only (excluding parenthesis, space and hyphens)
2. Not more than 10 characters
*/
var demoApp = angular.module('demoApp', []);
demoApp.directive('phoneInput', [ '$filter', '$browser', 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);
});*/
}
};
}]);
// existing code phoneFormatter filter
demoApp.filter('tel', [ '$window', function($window) {
return function(str, plain) {
if (!str) return str;
if (!plain) {
var trimmed = str.trim(),
patt = /\([0-9]{3}\)\s{1}[0-9]{3}\-[0-9]{4}/,
parsed = ['('];
if (trimmed && !patt.test(trimmed)) {
var arr = trimmed.split('');
angular.forEach(arr, function(val) {
if (parsed.length == 4) {
parsed.push(')'); parsed.push(' ');
}...