Restricting input to positive numbers in an input box with angularjs

I need to restrict the user to input only positive numbers in the text field

Here is my code snippet:

Contents of script.js file:

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();
    }
  });
}
};
});
});

Contents of angular.html:

<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 is it not functioning properly? Could someone please test and verify it!

Answer №1

To ensure only numerical values are accepted, switch the input type to number and utilize the min directive to set a minimum value constraint.

<input type="number" ng-model="user.age" placeholder="Please enter an age" min="0"/>

Answer №2

It appears that there are some issues with the code you have provided.

  1. Firstly, avoid nesting ng-app. Instead, use a single ng-app with multiple ng-controller.
  2. Make sure to include restrict within your directive to specify its usage (e.g., A=Attribute, E=Element, C=Class), such as using restrict: "A".
  3. When defining a controller, follow best practices by using an array format with the last element being the actual controller function and the preceding elements representing all the services or factories used in string format.
  4. @MajidYaghouti's suggestion to utilize ng-change is noteworthy. However, if you prefer directives, certain corrections need to be made to the existing code.
  5. Ensure proper code formatting and adopt meaningful naming conventions for clear understanding and elegance.

Here is a snippet of 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 this is a portion of 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>

You can view the updated plunkr here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Store the text area content as a JSON object

What is the best way to store the content of a textarea in JSON format? I am currently working on a project where I have a textarea element and I need to save its value into a JavaScript object. Everything is functioning correctly except when 'enter ...

Transitioning between modals using Tabler/Bootstrap components in a ReactJS environment

Currently, I am constructing a Tabler dashboard and incorporating some ReactJS components into it. Initially, I used traditional HTML pages along with Jinja2 templates. However, I have now started integrating ReactJS for certain components. I prefer not t ...

Update all items in the menu to be active, rather than only the chosen one

Here is the layout of my menu along with the jQuery code included below. The functionality is such that when I click on Home Page, its parent element (list item) receives an active class. Currently, when I am on the Home Page, the list item for Account Co ...

Node.js cannot access the uploaded image data as it has been defined as undefined

I have encountered an issue while sending an image file through ajax to my Node.js server. Upon attempting to view the file data, it returns 'undefined'. Here is a snippet from my app.js file: var express = require("express"); var app ...

Why do ES6 classes fail to set properties when an overloaded function is called within the constructor of the parent class?

I encountered a puzzling scenario while coding that has left me perplexed. Here's the situation: I am extending a class from a library, which serves as the "Parent"-class. It allows its subclasses to override the init-method for custom initialization ...

AngularJS score tracker malfunctioning

Can you please review this for me? http://plnkr.co/edit/i4B0Q2ZGiuMlogvwujpg?p=preview <input type="radio" name="op_0" ng-value="true" ng-model="n1"> True <input type="radio" name="op_0" ng-value="false" ng-model="n2"> False <input type="r ...

Methods for retrieving a file within a nodejs project from another file

Currently, my project has the following structure and I am facing an issue while trying to access db.js from CategoryController.js. https://i.sstatic.net/8Yhaw.png The code snippet I have used is as follows: var db = require('./../routes/db'); ...

Transmitting information between two controllers

For some reason, I can't seem to solve this seemingly simple issue. Within my AngularJS file, I have 2 controllers. analyzer.controller('AnalyzerController',function($scope,$http) { $scope.builds = []; $http.get('/List'). ...

Access an HTML element and using JavaScript to make changes to it

As a new web developer, I am eager to create a grid of file upload zones on my site. I have decided to use DropZone.js for this project. I have customized DropZone and added multiple drop zones in the HTML. The grid layout consists of four rows with four ...

What is the best way to restrict the amount of photos displayed on each page?

I am having an issue with displaying a set number of images on each page. Despite setting a maximum limit for the number of images shown, all the images are still appearing on any given page. Here is the PHP logic I have written: $counter = 0; foreach ...

Trigger a click event on a file input in Ionic 3 Android by using the Fire method

In my Ionic 3 project, I've enabled users to upload multiple images through the application. I am seeking a way to trigger the file browser to open when a Button is clicked, as shown below. Here is the snippet of code I am currently working with: hom ...

How does the 'Route' parameter serve in the Restangular methods oneUrl() and allUrl()?

Check out the signature for the oneUrl function: oneUrl(route, url). Here's what the documentation says: oneUrl(route, url): Using this will generate a new Restangular object that points directly to a single element with the specified URL. I fin ...

Is there a way to retrieve HTML generated by JavaScript?

The title may not be very clear, so let me give an example to explain: Imagine there are two websites, site A and site B, both related to finance. I am interested in comparing the value of Italian pizza on one specific page from each site to determine wh ...

The server encountered an error: TypeError - It is not possible to convert undefined or null into an

Check out this Code import { getProviders, signIn as SignIntoProvider } from "next-auth/react" function handleSignIn({ providers }) { return ( <> {Object.values(providers).map((provider) => ( < ...

Is it time to set up your own MySQL Database?

let connection = mysql.createConnection({ user: 'root', password: '1234', database: 'data101', port: 3306 }); While using the MySQL package for NodeJS to create a database, I have a question. Do I need to manually cr ...

How can I extract only certain keys from a large JavaScript object while keeping the code concise?

Simply put, I aim to streamline objects by discarding unnecessary keys. Imagine a scenario where a third party API sends back JSON data with numerous attributes that hold no importance to you. obj = { name: ..., id: ..., description: ..., blah: .. ...

Ways to center the percentage on the progress bar

I'm having an issue with positioning the percentage 100% in the center of the element. I attempted adjusting the spacing in the JavaScript code, but so far it hasn't been successful. Here is the current output for the code: http://jsfiddle.net/G ...

When implementing Firebase Cloud Messaging with React, the token generated by firebase.messaging().getToken() will vary with every refresh

I'm working on a React web app using Gatsby and I want to integrate push notifications through FCM. My firebase-messaging-sw.js service worker is set up, and I'm trying to retrieve a token using the following method in my app: messaging .req ...

Understanding the Impact of npm Dependencies on AAB (Android App Bundle) Release Size in React Native

Switching over to React-Native and Node.js from a Python background has left me confused about how dependencies are managed in React-Native (which I assume is similar to node.js). Query When creating a React Native AAB, are all Node Modules declared in th ...

Tips for efficiently expanding NodeJS while running it through an Apache web server?

Currently, I have Apache Web Server running alongside NodeJS on the same system but on different ports. I am reverse proxying to connect and use them for various purposes. My concern is how to scale this architecture up to accommodate around 10 million u ...