Created
April 1, 2017 11:30
-
-
Save deepal/79c8d9a281b39b32022b08cbde74b253 to your computer and use it in GitHub Desktop.
This file contains 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
(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