Validating the length of digits in an Angular JS number input - tips and tricks

Our goal is to create an input field that only allows values from 0 to 24 (for a time entry application).

These are the specific values users should be able to input:

0
1
2
3
4
5
6
7
8
9
00
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

The current code snippet looks like this:

HTML:

        <div class="list list-inset">
            <label class="item item-input">
                <input id="time" type="number" placeholder="24" ng-model="$parent.time1" ng-change="onChange(time1)">
            </label>
            <label class="item item-input">
                <input type="tel" placeholder="24" ng-model="time2" >
            </label>
        </div>

JS/Angular:

  var savedTime = 0;
   $scope.onChange = function(time) {
      if (time > 23 || currentTime > 2) {
        $scope.time1 = savedTime;
      } else {
        savedTime = time;  
      };
  };

While this restricts the input numbers, it does not prevent users from entering multiple preceding zeros, which is not desired.

I attempted using time.toString().length and implementing some validation based on that, but discovered that even when converting 00000 to a string, it still results in "0".

Is there a more effective way to limit the input to two digits?

Thank you.

Answer №1

To incorporate the saved time into your function, all you need to do is include

$scope.time1 = parseInt(savedTime)
at the end.

var savedTime = 0;
   $scope.onChange = function(time) {
      if (time > 23 || currentTime > 2) {
        $scope.time1 = savedTime;
      } else {
        savedTime = time;  
      };
      $scope.time1 = parseInt(savedTime);
};

Answer №2

One way you could limit input to a maximum of 2 characters is by using the [ng-maxlength="number"] directive. Simply set it to 2 in your code:

    <div class="list list-inset">
        <label class="item item-input">
            <input id="time" type="number" placeholder="24" ng-model="$parent.time1" ng-change="onChange(time1)" ng-maxlength="2">
        </label>
        <label class="item item-input">
            <input type="tel" placeholder="24" ng-model="time2" ng-maxlength="2">
        </label>
    </div>

Answer №3

Transform your input to adhere to a specific pattern:

<input type="text" ng-pattern="/^[A-Za-z]{1,10}$/" ...>

Answer №4

To achieve the desired effect, consider your intentions. You could implement a solution like the following:

<input type="text" ng-pattern="/[0-9]{1,2}/" 
               maxlength="2"
               ng-model="myCtrl.title">

This code snippet restricts users from inputting more than 2 characters. It also assigns the field class to ng-invalid-pattern if non-numeric characters are entered.

If you prefer displaying a validation message when a user types in three or more characters without preventing entry of two characters, simply eliminate the maxlength attribute.

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

Javascript function encountering difficulty accessing the 'this' variable

I am embarking on a new HTML5 game project, my very first one. Right now, I am working on creating a function that holds variables. While I cannot recall its exact name, I remember the process from a tutorial. In my attempt to set up some of these variable ...

What is the best way to utilize document.body in order to add a table to a designated DIV?

Once I make a copy of the table, my goal is to insert this new table into a designated DIV named div1. How can I add the new table to div1? <div id="div1"> </div> var copiedElement = document.getElementsByTagName("table" ...

The AJAX query for validating IDs in a JSP page consistently produces identical outcomes

I have been implementing a feature to check IDs using AJAX in JSP. When a user tries to create a new account, they enter the desired ID and AJAX checks if the ID already exists in the database. If the ID is found, it returns 'n' which is then dis ...

Issue with React and Mongoose: State Change Not Being Saved

I am facing an issue with changing the state of my checkbox. Initially, the default option in my Mongoose model is set to false. When a user checks the box and submits for the first time, it successfully updates their profile (changing the value to true). ...

Top technique for extracting json files from post requests using nodejs

Situation: I'm running a Node.js REST server that receives JSON files, parses them, and inserts them into a database. With an anticipated influx of hundreds of requests per second. Need: The requirement is to only perform insertions by parsing the JS ...

How to eliminate all special characters from a text in Angular

Suppose I receive a string containing special characters that needs to be transformed using filter/pipe, with the additional requirement of capitalizing the first letter of each word. For instance, transforming "@!₪ test stri&!ng₪" into "Test Stri ...

Struggling to retrieve the data from a RESTful API?

I'm currently learning how to fetch an API in javascript and I'm encountering some difficulties in extracting specific parts of the response body. My goal is to store the setup and punchline of a joke in variables for later use. Here is the code ...

Tips for modifying the color or personalizing the header arrow for the expandableRow within Mui Datatable

My MUI data table has the expandable rows option, along with an ExpandAll button in the header row. The arrow displayed in the title row is confusing for users as it's similar to the arrows in all other rows. I want to change the color of the header a ...

Why does JavaScript interpret the input [ 'foo' ] as accessing a property rather than declaring an array?

I find this particular dilemma on the Mocha Github issue tracker quite fascinating. https://github.com/mochajs/mocha/issues/3180 This snippet of code is functioning as intended: describe('before/after with data-driven tests', () => { befo ...

The Next.js build failed due to the absence of the required "slug" parameter being passed as a string

I'm currently working on setting up a blog using Next.js and TypeScript, and I've encountered an issue with [slug].tsx. The error message I'm receiving is: Build error occurred Error: A required parameter (slug) was not provided as a strin ...

`The header navigation is not responding to window resizing functionality`

I am currently developing a header navigation that consists of a logo on the left side, a profile icon on the right side, and some navigation links in the middle. A left slide menu has been implemented to trigger when the window width is less than 700px. ...

Identify alterations in django-bootstrap-datepicker-plus through JQuery

I am having an issue with the django-bootstrap-datepicker-plus package. I want to trigger an alert when the date changes, but it seems that JQuery is not detecting any modifications to the date field. Following the guidance in this question about detectin ...

When attempting to run the npm install mathjs command, an error is displayed

Trying to install mathjs using npm but encountering an error: npm install mathjs The error message received is as follows: npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write npm WARN tar T ...

Combine multiple arrays of JSON objects into a single array while ensuring no duplicates

Trying to combine two JSON arrays into one without duplicates based on date. The jQuery extend() function isn't doing the trick, so looking for an alternative solution that avoids nested $.each statements due to potential large dataset size... [ ...

Dealing with universal Ajax error handling in AngularJS

Previously on my website when it was 100% jQuery, I employed this method: $.ajaxSetup({ global: true, error: function(xhr, status, err) { if (xhr.status == 401) { window.location = "./index.html"; } } }); to establi ...

Using JavaScript to create temporary drawings on a webpage that automatically erase themselves

I am curious about how to achieve a scribble effect that self-erases, similar to what is seen on this website: Example: Thank you! I have come across some similar scripts, but I am struggling to understand how to make the scribble disappear after a few ...

What are some ways to keep the text within the boundaries of the input box?

How can I prevent the letters from extending beyond the bar when typing a lot of characters? Your assistance in resolving this issue is greatly appreciated. <div id="tasks-container"> <div id="tasks-header"> ...

The .change() function is only executing once and not triggered by multiple clicks

I have a JavaScript file that runs automatically through an HTML script. The issue I am facing is with the putToggleCall() function, which should be triggered every time one of the toggles is clicked. However, it only executes once, even before the docum ...

Displaying API data in HTML using AngularJS: A step-by-step guide

Hello! I am struggling to display the objects returned by an API in my HTML using the code below. Additionally, I would like to implement a filter to sort by id. angular.module('MainApp').controller('PhoneController', function ($scope ...

Tips for creating different CSS print layouts within a single-page application

I am working on a single page application with multiple sections that need to display a list of images on separate pages. I was considering using iframes for this task, but I'm looking for advice from someone who has experience with similar situations ...