I am trying to validate a number according to its min and max value through angularJS this is the custom directive, I first tried with max that provide angularJs for input number validation it works with static number not with binding data. That's why i thought about custom directive
.directive('ngMax', function() { return { restrict: 'A', require: 'ngModel', link: function(scope, elem, attr, ctrl) { scope.$watch(attr.ngMax, function(){ if (ctrl.$isDirty) ctrl.$setViewValue(ctrl.$viewValue); }); var maxValidator = function(value) { var max = scope.$eval(attr.ngMax) || Infinity; if (!isEmpty(value) && value > max) { ctrl.$setValidity('ngMax', false); return undefined; } else { ctrl.$setValidity('ngMax', true); return value; } }; ctrl.$parsers.push(maxValidator); ctrl.$formatters.push(maxValidator); } }; }); and in the view :
<div class="modal-body" > title: {{book.title}}<br> price: {{book.price}}<br> quantity: {{book.nbr_exemplaires}} <form name= "myForm" ng-submit= "addToCart(book, quantity, <%= current_user.id %>)" novalidate > <input type="number" min="1" ng-max="{{book.nbr_exemplaires}}" name= "quantite" ng-model="quantity" required > <span style="color:red" ng-show="myForm.quantite.$error.required"> <span ng-show="myForm.quantite.$error.required">quantity is required!</span> </span> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button class="btn btn-primary" ng-disabled="myForm.$invalid ">Save changes</button> </div> </form> I could not understand where is the problem