Skip to content

Instantly share code, notes, and snippets.

@fedyk
Last active October 24, 2015 18:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fedyk/1fe5a7c66a1a43d20d12 to your computer and use it in GitHub Desktop.
Save fedyk/1fe5a7c66a1a43d20d12 to your computer and use it in GitHub Desktop.
Angular Phone Validation
angular.module('myModule')
.directive('ngPhone', function() {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
function isPhone(str) {
var lengths = [7,10,11];
var number = (str || '').replace(/\D+/ig, '');
return lengths.indexOf(number.length) !== -1;
}
//For DOM -> model validation
ngModel.$parsers.unshift(function(value) {
var valid = isPhone(value);
ngModel.$setValidity('phone', valid);
return valid ? value : undefined;
});
//For model -> DOM validation
ngModel.$formatters.unshift(function(value) {
ngModel.$setValidity('phone', isPhone(value));
return value;
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment