Last active
October 24, 2015 18:50
-
-
Save fedyk/1fe5a7c66a1a43d20d12 to your computer and use it in GitHub Desktop.
Angular Phone Validation
This file contains hidden or 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
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