Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing user to type only positive numbers in input box using angularjs

I want to allow the user to enter only positive numbers in the textbox

My code is as follows:

script.js file contents:

angular.module("myfapp", []).controller("HelloController", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "AngularJS";
});

angular.module('myApp', []).controller('MainCtrl', function($scope) {
app.directive('validNumber', function() {
  return {
require: '?ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
  if (!ngModelCtrl) {
    return;
  }

  ngModelCtrl.$parsers.push(function(val) {
    var clean = val.replace(/[^0-9]+/g, '');
    if (val !== clean) {
      ngModelCtrl.$setViewValue(clean);
      ngModelCtrl.$render();
    }
    return clean;
  });

  element.bind('keypress', function(event) {
    if (event.keyCode === 32) {
      event.preventDefault();
    }
  });
}
};
});
});

angular.html contents as follows:

<html>
<head>
<script src="angular.min.js"></script>
<script src="script.js"></script>

<style>
.entry {
width: 300px;
margin: 10px auto;
text-align: center;
}
</style>

</head>
<body ng-app="myfapp">
<div ng-controller="HelloController" >
<h2 class="entry">Welcome {{ helloTo.title }} to the world of        Tutorialspoint!</h2>
</div>

<section ng-app="myApp" ng-controller="MainCtrl">
 <h4 class="entry">AngularJS Numeric Value Widget</h4>
<div class="well entry">
<label>Employee Age
  <input type="text" ng-model="employee.age"  placeholder="Enter an age"    valid-number/>
   </label>
</div>
</section>

</body>

</html>

Why does it not work? Can anyone run it and check please!

like image 595
Clyde Dias Avatar asked Jan 06 '16 09:01

Clyde Dias


2 Answers

Change your input type to number, then you can use min directive to specify the minimum number allowed.

<input type="number" ng-model="employee.age" placeholder="Enter an age" min="0"/>
like image 81
Majid Yaghouti Avatar answered Nov 01 '22 20:11

Majid Yaghouti


There are a lot of problems with your code.

  1. you've nested ng-app which is not allowed normally, use a single ng-app with multiple ng-controller.
  2. your need to use restrict inside your directive to restrict its usage to one or multiple types (i.e. A=Attribute,E=Element,C=Class), like in this case restrict: "A"
  3. When specifying a controller its generally a good practice to use array with the last element being the controller function and the first ones being all the services factories you are using in string format
  4. @MajidYaghouti's suggestion is good to use ng-change but if you insist on using directives I have done some bit of corrections to your code.
  5. Use some code formatting dude, and name your stuff cautiously and elegantly.

your script.js

angular.module("myfapp", []).controller("HelloController", ["$scope", function($scope) {
        $scope.helloTo = {};
        $scope.helloTo.title = "AngularJS";
    }])
    .controller('MainCtrl', ["$scope", function($scope) {

    }])
    .directive('validNumber', function() {
        return {
            restrict: "A",
            require: '?ngModel',
            link: function(scope, element, attrs, ngModelCtrl) {
                if (!ngModelCtrl) {
                    return;
                }

                ngModelCtrl.$parsers.push(function(val) {
                   if (val === null)
                    return;
                   var myRegex = /\d+\.(\d{1,2})?/;
                   var clean = myRegex.exec(val)[0];
                   if (val != clean) {
                       ngModelCtrl.$setViewValue(clean);
                       ngModelCtrl.$render();
                   }
                   return clean;
                });

                element.bind('keypress', function(event) {
                    if (event.keyCode === 32) {
                        event.preventDefault();
                    }
                });
            }
        };
    });

and your index.html

<html>
   <head>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
      <script src="script.js"></script>
      <style>
         .entry {
         width: 300px;
         margin: 10px auto;
         text-align: center;
         }
      </style>
   </head>
   <body ng-app="myfapp">
      <div  ng-controller="HelloController" >
         <h2 class="entry">Welcome {{ helloTo.title }} to the world of        Tutorialspoint!</h2>
      </div>
      <section ng-controller="MainCtrl">
         <h4 class="entry">AngularJS Numeric Value Widget</h4>
         <div class="well entry">
            <label>Employee Age
            <input type="text" ng-model="employee.age"  placeholder="Enter an age"  valid-number/>
            </label>
            <div>
               {{ employee.age }}
            </div>
         </div>
      </section>
   </body>
</html>

updated plunkr

like image 40
Minato Avatar answered Nov 01 '22 20:11

Minato