Creating a specialized Angular directive for handling input of positive numbers

I am working on an application that requires a text field to only accept positive integers (no decimals, no negatives). The user should be restricted to entering values between 1 and 9999.

<input type="text" min="0" max="99" number-mask="">

While searching online, I came across this JSFiddle which unfortunately accepts negative integers and is not compatible with Internet Explorer.

I am relatively new to writing directives and currently learning Angular. I use TypeScript for generating Angular in my .NET MVC project.

Here is the code snippet:

var app = angular.module('myApp', []);

app.directive('numberMask', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            $(element).numeric();
        }
    }
});

I am wondering if it's possible to add a check for negative numbers in the code. Something like:

if(element < 0 && element.length > 4)
  .....
else
  ....

Thank you in advance!

Answer №1

angular module 'myapp', []
custom directive 'numberMask' for input field validation
function to ensure input values are within specified range
    on keyup event, check if value is between min and max
        if not, revert back to previous valid value
<p><a href="http://jsfiddle.net/9HgBY/" rel="nofollow">Demo Link</a></p>

Answer №2

I incorporated modifications to Adrian's solution to include support for ng-model usage. While the code may not be the most aesthetically pleasing, it effectively accomplishes the task at hand.

angular.module('myapp', [])
.directive('numberMask', function () {
    return {
        require: 'ngModel',
        restrict: 'A',
        link: function (scope, elem, attrs, ctrl) {   
            var oldValue = null;
            scope.$watch(attrs.ngModel, function (newVal, oldVal) {
                var min = parseInt(attrs.min) || 0;
                var max = parseInt(attrs.max) || 10;
                if (!between(newVal, min, max)) {
                    if (newVal > max)
                        ctrl.$setViewValue(max);
                    else if (newVal < min)
                        ctrl.$setViewValue(min);
                    else
                        ctrl.$setViewValue(oldValue);
                    ctrl.$render();
                }else{
                    oldValue = newVal;
                }
            }, true);

            function between(n, min, max) { return n >= min && n <= max; }
        }
    };
});

You can view Adrian's original fiddle with my enhancements 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

The server gets blocked by numerous AJAX GET requests happening at the same time until the data gets returned

In my Rails application, I am using the gridList library to display charts. The chart data is fetched asynchronously from a controller method in JSON format via AJAX. Upon initial page load, each gridlist item displays a loading icon while simultaneously m ...

Retrieving information from an ajax array in PHP

I am currently attempting to retrieve an array of data using AJAX on the PHP side, but I am facing difficulties in accessing the values in PHP. Here is my JavaScript code snippet: console.log(obj); $.ajax({ method: 'POST', url: '/in ...

What is preventing this Javascript from running in Firefox and Chrome?

I recently encountered an issue with some Javascript code that functions correctly in Internet Explorer, but fails to work on Mozilla Firefox or Google Chrome. Any insights as to why this might be the case? function returnData(strCode,strProgramCode,strNa ...

Can a ng-repeat value be assigned to a text input field?

<tr ng-repeat="person in users" ng-class="{'chosen': person.AdmissionID == currentSelection}" ng-click="selectRow(person.AdmissionID)"> <td>{{person.AdmissionID}}</td> <td>{{person.AdmissionNumber}}</td> ...

AngularJS 500 server error

In my current project, I am developing a straightforward angularjs - J2EE application that fetches data from a mysql server and then displays it on an HTML page. The angular function is triggered on form submission as shown below: <div id="register_for ...

Troubleshooting: Unable to Display Image and Text in Ionic View Header

I have successfully created a code snippet that allows me to attach an image and text to the header bar of an Ionic view. Here is the code: <ion-view align-title="left"> <h1 style="margin-left:100px" class="title"> <img class="title-image" ...

What is the best way to calculate the number of items in your mongoose reference with a specific field?

I am trying to calculate the number of active Workers that belong to a specific company. Here is an example scenario: const workerSchema = new Schema( { userId: { type: Types.ObjectId, ref: 'User', ...

Angular's implementation of a web socket connection

I am facing an issue with my Angular project where the web socket connection only opens upon page reload, and not when initially accessed. My goal is to have the socket start as soon as a user logs in, and close when they log out. Here is the custom socke ...

Experiencing a problem with value formatting while attempting to implement tremor for charts in React with Next.js version 13

import { getAuthSession } from "@/lib/auth"; import { db } from "@/lib/db"; import { Card, LineChart, Text, Title } from "@tremor/react"; import Linechart from "./LineChart"; const dollarFormatter = (value: number) ...

encountering an issue while working with Selenium on Google Colab

I'm attempting to perform web scraping with selenium in Google Colab and running into some errors The webpage is prompting me to enable JavaScript and disable any ad blockers. I tried enabling JavaScript by adding the following line of code: chrome_o ...

Search the table for checked boxes and textboxes that are not empty

Could you suggest alternative ways to express the following scenario? I have a table with 3 rows. Each row contains a column with 3 checkboxes and another column with just a text box. I would like it so that when the values are retrieved from the database ...

The behavior of Quasar's q-drawer is quite unpredictable

Having made the transition from Vue.js 2 with Vuetify to Vue.js 3 with Quasar due to Vuetify not officially supporting Vue.js 3 yet, I am utilizing q-drawer and its mini property. This allows me to toggle between the mini state and the normal expanded stat ...

Sending an HTTP post request with form data and various field controls will not be directed to a Java backend

Recently, I've started working with AngularJs and I'm facing an issue with uploading image files along with their labels through a Jax-RS post rest API. My problem is that the control in my AngularJS controller is not entering the Java post API. ...

Display the logout button in AngularJS upon clicking the SignIn button

I have a login form in a specific partial that is displayed within the main page's body. The file for the login form is named login.html. <form name="loginForm" class="form-horizontal" ng-controller="loginController" ng-submit="submit()" noval ...

AngularJS - Multi-controller Data Calculation

I am currently in the process of developing an Angularjs application. The project is quite extensive and requires segmentation into multiple Controllers to manage effectively. One challenge I am facing is performing calculations across these controllers. ...

Creating a toggle feature using ng-switch

I'm having trouble getting this code to function correctly as a toggle. Can anyone offer any suggestions on what might be causing the issue? <div ng-switch="!!myvar"> <a ng-switch-when="false" ng-click="myvar = true" style="cursor:poin ...

Pause the YouTube video when the modal is closed, following an AJAX load

I'm facing an issue with a small script that is supposed to stop YouTube videos from playing once their modals are closed. The problem arises when the HTML content is loaded through AJAX. Here is the script: $('#panelModal-1').on(&apos ...

Launching a segment from a different page within a foundation reveal modal

With the goal of displaying a modal that contains content from a section on another page when a link is clicked, I encountered a specific issue. For instance: <a href="/otherpage" data-reveal-id="myModal" data-reveal-ajax="true"> Click Me For A Mod ...

How can I use Angular to toggle a submenu based on a data-target attribute when clicked?

Struggling to implement a functionality using ng-click to retrieve the data-target attribute of a clicked angular material md-button, in order to display the submenu when a topic is clicked on the sidenav. The navigation structure consists of md-list with ...

JavaScript anchor scrolling

I am currently working on building a website with anchor navigation similar to what is used on platforms like Facebook and Google Mail. I have managed to get it partially working, but there are still some issues. For example, when I load the page with some ...