Skip to content

Instantly share code, notes, and snippets.

@nklatt
Last active August 29, 2015 14:18
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 nklatt/17a9a62297ae277550d9 to your computer and use it in GitHub Desktop.
Save nklatt/17a9a62297ae277550d9 to your computer and use it in GitHub Desktop.
Extending Angular number inputs to validate for step attribute
angular
.module('myApp', [])
.directive("step", function() {
return {
restrict: "A",
require: "ngModel",
link: function(scope, element, attributes, ngModelCtrl) {
ngModelCtrl.$validators.step = function(modelValue, viewValue) {
var isValid = true; // assumed innocent until proven guilty
if ( ! ngModelCtrl.$isEmpty(modelValue) ) { // empty is okay
var $element = $(element); // jQuery? that's lame, you hack
var value = parseFloat($element.val());
var min = $element.attr("min") || 1;
var max = $element.attr("max") || value;
if ( value // don't flag value of zero
&& value >= min // only flag increment if they've met the minimum
&& value <= max ) { // only flag increment if they've met the maximum
var step = $element.attr("step") || 1;
if (value % step) {
isValid = false;
}
}
}
return isValid;
}
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment