Retaining original input value even when validation is applied with input type="number"

Encountering an unusual scenario while using angularJs and input type="number". It seems that if the initial value of an input falls outside the specified min and max range, the value gets wiped out.

To better visualize the issue, I created a fiddle - http://jsfiddle.net/PK3QH/2/

Here's the HTML code snippet:

<div ng-controller="MyCtrl">
    <input ng-model="bindData.SomeAmount" type="number" required="required" />
    <br />
    <input ng-model="bindData.SomeAmount" type="number" required="required" 
        min="2" max="10" />
</div>

And here's the accompanying JavaScript:

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

function MyCtrl($scope) {
    $scope.bindData = {
        SomeAmount: 1
    };
}

The first textbox works fine, however, in the second one the value doesn't display. The challenge is to maintain the value while ensuring it is within the specified range. Any suggestions on how to achieve this?

Answer №1

It seems evident that a bug is present in this scenario.

The issue arises due to the fact that formatters are being applied before validators. Specifically, in the case of 'number'

  if (attr.min) {
    var minValidator = function(value) {
      var min = parseFloat(attr.min);
      return validate(ctrl, 'min', ctrl.$isEmpty(value) || value >= min, value);
    };

    ctrl.$parsers.push(minValidator);
    **ctrl.$formatters.push(minValidator);**
  }

It appears that all the $formatters run prior to the initial execution of validators...refer to NgModelController for more clarity.

I am curious if during the "first" instance when $dirty != true, the formatters adhere to validity and withhold if validation yields false.

In the context of minNumber, should the formatter solely be limited to numbers? Why include it for minNumber?

This concern has been raised at https://github.com/angular/angular.js/issues/8264

As an interim solution until addressed by the Angular team, one might consider utilizing a custom directive instead of 'min'.

Answer №2

In my opinion, there seems to be a glitch in the system.

If you take out the ng-model attribute, the initial value becomes visible again.

If this is not considered a glitch, then when we type an invalid value like 40, it should not display the entered text as if nothing changed from the initialization. This lack of consistency is noticeable.

This inconsistency only occurs the first time the input directive is activated.

In my humble opinion, even if the model value is null, it should still retain the original value instead of clearing it.

I apologize for not offering a solution at this time.

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 comparison between "rxjs-tslint" and "rxjs-tslint-rules" npm packages

Previously, I utilized the rxjs-tslint-rules package to identify RxJS-related issues in my projects. This package was included in the devDependencies section of my projects' package.json files. Now, there is a new rxjs-tslint package that introduces ...

Assign a value to the Angular directive for the SharePoint People Picker

In my create form, I have successfully used a directive to capture and store values in SharePoint via REST. The directive I am using can be found at this link. Within my HTML, I am implementing the directive like this: <sp-people-picker name="CC" id=" ...

Leveraging angular.extend() with controllers and function overrides

Currently, I am working with Angular 1.4.8 and attempting to expand a controller. The original controller and the expanding controller are quite similar, but there is a specific function that I aim to replace in the extending controller. angular.module(&a ...

Use AngularJS to synchronize items on the same row based on user input in the first column

<td align="center"><input type="number" name="test" ng-model="item.qty" ng-model-options="{ updateOn: 'blur' }" ng-change="Save(item.qty, item.qty2, item.include, {{$index}})" /></td> <td align="center"><input type="n ...

Retrieving HTML Content with Ajax

Currently using this script for an assignment in my class. Still learning! The script checks whether a site is down or not. I want to expand this script to display statuses for each website in the table without duplicating the script. Any suggestions on ...

Why does parsing the GET response fail intermittently with Jquery, ajax, and JSON?

Currently, I am encountering an issue with ajax calls using jQuery where the response being returned is a JSON array. In certain scenarios, everything works perfectly fine. However, in other cases specifically in browsers like Firefox and IE11, there seems ...

Using a Default Value in a Destructured Function Parameter Results in a ReferenceError

When working on setting a default value for the db in my CRUD functions for testing purposes, I encountered a peculiar issue that has left me puzzled. Here's the snippet of code that caused the trouble: import { db } from './firebase' func ...

There appears to be a JavaScript validation error occurring on the current page, however, you are able

For my datepicker, I want an error message to display if the user selects a date more than 5 years in the future, saying "You are ineligible for our program". The user should not be able to proceed to the next step unless this error message is ad ...

Having trouble with filtering an array using the some() method of another array?

When utilizing the code below, my goal is to filter the first array by checking if the item's id exists in the second array. However, I am encountering an issue where the result is coming back empty. dialogRef.afterClosed().subscribe((airlines: Airli ...

How can I implement a for loop in Node.js?

I am currently experiencing an issue with my for loop while attempting to retrieve data from MongoDB and display it in the browser. The problem is that it only iterates through once, resulting in only the first entry being output. Strangely enough, when ...

Using ReactJS to create a Stacked Bar chart

I am encountering some challenges while trying to create a single stacked bar graph using data from an API. 1- The data I receive is not rounded, even when using % values. 2- Additionally, the total percentage does not always add up to 100%, causing the ...

Fixing issues with sending a GET request using $http

Despite passing a parameter, I am unable to reach the endpoint Attempting to send an id to the endpoint for a GET request controller.js var vid = $routeParams.vidId //retrieve the video id console.log(vid) //successful $http({ ...

Transform the v-model value from numerical to textual representation

Currently, I am using the <q-select> component and populating it with options fetched from an API. The issue arises when setting the value as the ID of the object, which is a number while the component expects a string, resulting in an error. <s- ...

Using JavaScript, extract current date from an API data

Here is an example of how the data from my API appears: const data = [{ "id": "1", "name": "Lesley", "creationDate": "2019-11-21 20:33:49.04", }, { "id": "2", "name": "Claude", "creationDate": "2019-11-21 20:33:09.397", }, { "i ...

Input Error in ASP.NET JavaScript

Within my ASP.NET website, I have implemented an <asp:TextBox /> where the text input is encoded using HttpUtility.HtmlEncode(); Furthermore, the page is equipped with validation controls like <asp:RequiredFieldValidator /> and <asp:CustomV ...

What are the steps to create a shadow effect on a bar chart in ChartJs?

Currently, I am utilizing version 3.9 of chartjs to construct a bar chart. My goal is to incorporate a shadow effect on the bars resembling the image in this link: https://i.sstatic.net/SGIrO.png Despite my efforts, I have not been able to locate instruc ...

Is it possible for .getElementByClassName to identify Ajax.GET elements?

I've run into a problem that I need help with: The issue arises when I have an API that makes an Ajax GET request. In the success function, it creates a button, a div, and several span elements with information inside, each with its own class. The GE ...

The 'Bfrip' button is missing from the DOM

Having some issues with displaying table content using DataTables. Everything seems to be working smoothly except for the Buttons, which are not appearing as expected. <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.1 ...

[ERROR_HTTP_HEADERS_ALREADY_SENT]: Headers can't be set once they have been sent to the client, expressjs

Whenever I attempt to insert data into my MySQL database using the express router function, I encounter an error. It appears that my server is trying to send a response twice, but I am unsure of where the issue lies. Here is the error message: throw err; / ...

Enabling the acceptance of blank values within an HTML5 date input field

When using an HTML5 date input for a field that corresponds to a nullable datetime column in the database, how can one avoid setting an empty value in the input field? In my AngularJS application, the ng-model is connected to a scope variable with an init ...