5

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!

2
  • 1
    suggestion: change your module name from myfapp to MyFirstApp sounds nicer.. :P Commented Jan 6, 2016 at 10:03
  • haha...il keep that in mind for the second one.... :-D Commented Jan 6, 2016 at 10:12

2 Answers 2

19

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"/>
Sign up to request clarification or add additional context in comments.

4 Comments

i want to do it using angularjs
If you mean you want to do it in controller or directive, use ng-change = "checkFunction()", so you can check the entered number in your controller.
I love these one-line solutions. Nothing against the 20+ lines of code solutions, but if it can be done in one, let's try it!
@Prashant Prabhakar Singh Are you using angularjs?
2

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

3 Comments

thanks a lot...the code works perfectly. now what if i wanted to enter only positive numbers and decimal numbers with just two numbers after the decimal
now what if i wanted to enter only positive numbers and decimal numbers with just two numbers after the decimal
ng-app is nestable. if i have multiple apps, they should all be able to run.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.