"Performing validation on a number input by using the ng-change event

Im using a number input that dynamically sets the min and max values based on another form field. I have two scenarios:

  • Level 1: Min = 2, Max = 50
  • Level 2: Min = 5, Max = 1000

I've set up an ng-change event on the input field to check if the entered number follows the rules for each level. If the number is too high or too low, it gets reset to the minimum.

<input type="number" step="1" ng-change="isValid()" ng-model="level.num" min="{{minNum}}" max="{{maxNum}}">

$scope.isValid = function () {
    if( ($scope.level.num > $scope.maxNum) || ($scope.level.nums < $scope.minNum)) {
        $scope.tooMany = true;
        $scope.level.num = $scope.minNum;
    }
};

The issue I'm facing is that when I select Level 1 and try to enter "15", as soon as I type "1" it automatically changes to 2. How can I ensure the number only changes when the user has finished entering their input?

Answer №1

In my opinion, a great approach would be to utilize blur as the determining factor for enforcing the minimum number requirement. This method can serve as a common scenario, such as when setting a minimum limit of 3 and having an input value of 24. By incorporating this into a single function, you are able to streamline the process while still upholding the underlying logic.

<input type="number" step="1" ng-blur="checkValidity(true)" ng-change="checkValidity(false)" ng-model="data.num" min="{{minValue}}" max="{{maxValue}}">

$scope.checkValidity = function (isBlurred) {  
    if (($scope.data.num > $scope.maxValue) || ($scope.data.num < $scope.minValue && isBlurred)) {
        $scope.invalidInput = true;
        $scope.data.num = $scope.minValue;
    }
};

Answer №2

If you happen to be utilizing angular 1.3, there is a feature called ng-model-options that may come in handy: example

<input type="text" ng-model="name" ng-model-options="{ updateOn: 'blur' }">

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

I'm curious about why I'm receiving the error "Unable to bind to 'ngFor' since it is not recognized as a property of 'li'. Can someone please explain why this is happening?

The issue is related to the *ngFor directive for nonvegfoodlist app.component.ts import { Component } from '@angular/core'; export class Menu { id : number; name :string; } const veg : Menu[] = [ { id:1 , name:'Rice'}, { id: ...

To modify the specified variables in data, I must deconstruct the object

Hello everyone, this is my debut post. I am seeking assistance with destructuring in order to update a variable that is defined within the "data" section. Below are the code snippets I have been working on using Vue. data: () => ({ id: '' ...

Emulate the selection process using element-ui and vue-test-utils

During my unit tests using Jest and Element-ui in Vue, I encountered an issue with a component containing a select element with 2 options. After selecting an option from the dropdown, I needed to verify that a specific action was called. 1) Everything wor ...

Managing multiple URLs in a MEAN Stack application

Currently, I'm working on a MEAN stack project to implement a CRUD system for managing courses. One specific aspect that is giving me trouble is figuring out how to handle unique URLs for each course I create. As of now, I am using routeprovider for t ...

How can I resolve the issue of using string values for items inside v-autocomplete, but needing them to be numbers in v-model?

I am working with a v-autocomplete component <v-autocomplete v-model="addressRegion" :items="selectLists.regions" item-value="key" item-text="value" ></v-autocomplete> The AddressRegion is curren ...

Tips on utilizing setInterval in a Vue component

When defining the timer in each individual my-progress, I use it to update the value of view. However, the console shows that the value of the constant changes while the value of the view remains unchanged. How can I modify the timer to successfully change ...

Can an unresolved promise lead to memory leaks?

I have a Promise. Initially, I created it to potentially cancel an AJAX request. However, as it turns out, the cancellation was not needed and the AJAX request completed successfully without resolving the Promise. A simplified code snippet: var defer = $ ...

Tips for launching different web browsers via hyperlinks?

My app has a link that I want mobile users from apps like LinkedIn to open in a browser such as Safari. I attempted this: <a href="safari-https://meed.audiencevideo.com">May open on Safari</a>' However, when I click the link, it opens i ...

Prevent selection based on function in Angular

I'm attempting to prevent certain options from being selected based on a specific method. For instance, let's say I have four options: A B C D In my method (let's use "x" as an example): if(name == A) { disable the selection for option A. ...

What is the best way to implement a composite primary key in DocumentClient.batchWrite()?

I am attempting to conduct a batch delete process based on the instructions provided in this documentation. The example given is as follows: var params = { RequestItems: { /* required */ '<TableName>': [ { DeleteRequest: ...

Transferring a PHP array to JavaScript using AJAX

I have spent time searching for answers to my issue with no success. My PHP file includes the following array: $data = ['logged' => $_SESSION['loggedin'], 'sessName' => $_SESSION['name']]; echo json_encode($dat ...

What should be the output when ending the process using process.exit(1)?

I need to update my code by replacing throw new Error('Unknown command.') with a log statement and process.exit(1);. Here is the example code snippet: private getCommandByName = (name: string): ICommand => { try { // try to fetch ...

Cassandra encountered a TypeError stating that the "value" argument is exceeding the bounds

I keep encountering the error message below. Any thoughts on what might be causing it? TypeError: "value" argument is out of bounds at checkInt (buffer.js:1041:11) at Buffer.writeInt32BE (buffer.js:1244:5) at Encoder.encodeInt (/ ...

How can I link two separate webpages upon submitting a form with a single click?

Here is a snippet of my code: <form action="register.php" method="post"> <input type="text" name="uname"> <input type="submit" > </form> Within the register.php file, there are codes for connecting to a database. I am looking ...

Extract data from JSON in Google Sheets

UPDATE: entry.content.$t is actually not the correct field to access individual cells. The proper method is using entry.gsx$[cell column header]. Thank you for pointing out this mistake and assisting in finding a solution. Initial inquiry: I am currently ...

Tips for shuffling the sequence of EJS variables

I am currently working on creating a quiz that consists of multiple choice questions. In order to display the Question, Correct Answer, and 3 other wrong options, I am utilizing EJS variables. The format will be similar to the following example: Question: ...

Improved method for transferring Mongodb query information to Pug

I'm seeking a more efficient method of passing data to my index.js file in a web development application. With only about a month of experience in web development, I acknowledge that this challenge likely stems from my lack of expertise. Here is the w ...

No data received from XMLHttpRequest

Within my Java Web application, I'm making an ajax request using the following code: <script type="text/javascript"> function selectTableHandler() { console.log("inside selectTableHandler"); var xhttp = new XMLHttpRequest(); var se ...

Creating a promise around a MongoDB instance in Node.js

Currently I am developing a web application where I need to create a MongoDB singleton connection that can be reused in different modules. My approach involves using promises, and so far this is what I have attempted: Server.js module.exports = new Promi ...

Seeking out the correct method for structuring loops and callbacks within nodejs with an emphasis on asynchronous operations

I've been researching multiple posts and articles on this topic, but I'm still struggling to grasp it. In my Mongoose model, there's a piece of code dedicated to inviting people to a project. When given a list of invitees, the code checks i ...