Skip to content

Instantly share code, notes, and snippets.

@zenius
Last active June 3, 2019 07:02
Show Gist options
  • Save zenius/f7be1f7bf0e0d0d69f17611449a0d16b to your computer and use it in GitHub Desktop.
Save zenius/f7be1f7bf0e0d0d69f17611449a0d16b to your computer and use it in GitHub Desktop.
Custom validations in Angular JS are created as directives with a dependency on the ng-model directive.
app.directive('evenNumber', function() {
return {
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
function isEven(value) {
if (parseInt(value, 10) % 2 === 0) {
ctrl.$setValidity('even', true);
} else {
ctrl.$setValidity('even', false);
}
return value;
}
ctrl.$parsers.push(isEven); // Do not forget this
}
};
});
Remember, when naming a directive, you must use a camel case name(like evenNumber) but
when invoking it, you must use - separated name (like even-number).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment