Skip to content

Instantly share code, notes, and snippets.

@joelhooks
Created March 16, 2013 20:10
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 joelhooks/5178094 to your computer and use it in GitHub Desktop.
Save joelhooks/5178094 to your computer and use it in GitHub Desktop.
module.directive('validatePhone', function () {
return {
require: 'ngModel',
link: function (scope, elem, attr, ngModel) {
function validatePhone(field) {
//regex squirreled from here: http://blog.stevenlevithan.com/archives/validate-phone-number
var regexObj = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
return regexObj.test(field);
}
function validate(value) {
var valid = validatePhone(value);
ngModel.$setValidity('phone', valid);
return valid ? value : undefined;
}
//For DOM -> model validation
ngModel.$parsers.unshift(function (value) {
var valid = validatePhone(value);
ngModel.$setValidity('phone', valid);
return valid ? value : undefined;
});
//For model -> DOM validation
ngModel.$formatters.unshift(function (value) {
ngModel.$setValidity('phone', validatePhone(value));
return value;
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment