0

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

1
  • 2
    I will warn you about using "NG" prefix: if you have to upgrade to angularJS 10.7, who will know if they will implement a ngMax directive? In this case you will encounter some errors.. Commented Dec 26, 2014 at 15:56

1 Answer 1

1

To avoid X/Y questions, when you try something and it doesn't work, try to address that first. That's good that you provided a broader context, so specifically to your question, built-in max provides everything that you need:

<input type="number" max="{{max}}" ng-model="foo"> 

and you can set max dynamically, for example:

$scope.max = 10; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.