Skip to content

Instantly share code, notes, and snippets.

@deepal
Created April 1, 2017 11:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save deepal/79c8d9a281b39b32022b08cbde74b253 to your computer and use it in GitHub Desktop.
Save deepal/79c8d9a281b39b32022b08cbde74b253 to your computer and use it in GitHub Desktop.
(function () {
angular.module('myformApp')
.directive('nameValidator', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, model) {
function validateName(name) {
let errors = [];
if (!name){
errors.push('required');
return errors;
}
if (name.length < 2){
errors.push('min_length');
}
if (!/^[a-zA-Z ]+$/.test(name)) {
errors.push('invalid_chars');
}
return errors;
}
function setValidity(errors) {
Object.keys(model.$error).forEach((k) => model.$setValidity(k, true));
errors.forEach((val) => model.$setValidity(val, false));
}
model.$parsers.unshift(function (viewValue) {
setValidity(validateName(viewValue));
return viewValue;
});
model.$formatters.unshift(function (modelValue) {
setValidity(validateName(modelValue));
return modelValue;
});
}
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment