Skip to content

Instantly share code, notes, and snippets.

@bradberger
Last active September 27, 2016 08:15
Show Gist options
  • Save bradberger/16b7f9e7eb91fc2ea81f to your computer and use it in GitHub Desktop.
Save bradberger/16b7f9e7eb91fc2ea81f to your computer and use it in GitHub Desktop.
A simple AngularJS directive to make sure a number is not zero. It sets the formName.elementName.$error.zero value accordingly.
/**
* @description A simple check to ensure a number is not zero. Sets the "zero" validation accordingly.
* @usage <input ng-model="myModel" not-zero>
*/
angular.module("app").directive("notZero", function() {
var linkFunc = function(scope, element, attrs, ngModel) {
var zeroValidator = function(value) {
var num = parseFloat(value);
ngModel.$setValidity("zero", ! isNaN(num) && num !== 0);
return value;
};
ngModel.$parsers.push(zeroValidator);
ngModel.$formatters.push(zeroValidator);
};
return {
require: "ngModel",
link: linkFunc
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment