"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

How can I transform an HTML div into a video file like MP4 using Python and Django?

I'm looking to take a HTML page and target a specific <div> within it in order to convert it into video format. Purpose: I understand that HTML is typically static, but I have a requirement to transform it into a video. I'm seeking method ...

Prevent dropzone from refreshing the page

For the past few days, I have been scouring the internet for solutions on how to prevent a page from automatically reloading after an upload. Despite finding various methods, I have been unsuccessful in resolving this issue. Although I am following the st ...

Issue with React and JavaScript: Object is displayed on the console briefly before disappearing

I am having an issue with my sign up page where the console log of the two fields disappears after a second. I would appreciate any assistance on this matter. Below is the code for the sign-up form: export default function SignUp() { const [firstNam ...

What are the reasons behind the min and max range method not providing accurate results?

I am in need of a method that can verify if a given value falls within the valid range of -064.000000 to -180.000000 and 142.000000 to 180.000000. The structure of my ranges object is as follows: "ranges": { "range1": { "min& ...

Unable to substitute a value using the useState hook in React

Whenever I click a key, I attempt to update the value of a variable but it appears not to be working as intended. ↓ The current implementation is not effective and needs improvement import React, { useState, useEffect } from 'react'; const Li ...

Guide on implementing a template within a form using Vue.js

I have set up a Vue instance for handling the form data var formInstance = new Vue({ el: '#amount_form', data: { logdate: '', amount:'', description:'' }, methods: { ...

I received no response when I checked my Discord messages

I'm currently working on creating a bot that will send a daily morning message at 9 o'clock with a customizable reaction. Right now, it's successfully sending the message on Discord but there seems to be an issue with the reaction part. Can ...

Using Rails 6 to trigger a JavaScript function after rendering a partial

Newbie in Rails and Javascript here, During a training project, I implemented a feature where flash messages automatically disappeared after a few seconds using JQuery. When a visitor added a product to their cart through an AJAX request, a flash partial ...

Dynamically add a CSS class to the <head> tag in real

Within this function, my goal has been to dynamically append gradClass in order to apply a gradient background to a div. function applyGradient(upto) { var gradStyle = "background: -webkit-linear-gradient(left, #ff1a00 20%,#ffffff 30%);" ...

What could be causing the malfunction with Angular?

What seems to be the issue? <!doctype html> <html lang="en" ng-app='SOO'> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div ng-controller='someController ...

Is there a way to create Angular components sourced from an external library using JavaScript?

I'm currently developing an Angular project and leveraging an external component library called NGPrime. This library provides me with a variety of pre-built components, including <p-button> (which I am using in place of a standard <button> ...

Obtaining a string from a regular expression does not function as anticipated

Currently, I am in the midst of a project that requires me to identify specific HTML tags and replace them with others. To accomplish this task, I am utilizing JavaScript, and the code snippet looks like this: // html to update html = '<div cla ...

I'm looking to enhance my code by adding a new user login password. How can I achieve this?

Currently, I am in the process of adding another user and have been exploring various code snippets available on different websites. I decided to test the following example, which worked perfectly. However, I am now wondering how I can add an additional u ...

Encountering difficulties in JavaScript while trying to instantiate Vue Router

After following the guide, I reached the point where creating a Vue instance was necessary (which seemed to work). However, it also required providing a Vue Router instance into the Vue constructor, as shown below. const router = new VueRouter({ routes }) ...

What is the method for retrieving the currently selected value in a MultiColumnComboBox within Kendo for Angular?

Check out this live example created by the official Telerik team: I need to extract the id (referenced in contacts.ts) of the currently selected employee when clicking on them. How can I access this information to use in another function? ...

Ways to host static content in ExpressJS for specific directories and exclude others

I need to configure my ExpressJS server to serve static files from specific paths only, excluding others. For example, I want to serve static files from all paths except /files where I only need to manipulate a file on the server. Currently, my code looks ...

Issues with AJAX requests failing to fire with the latest version of jQuery

A small script I have checks the availability of a username in the database, displaying "taken" if it's already taken and "available" if it's not. The code below works perfectly with jQuery v1.7.2. However, I need to update it for jQuery v3.2.1. ...

The file raphael.2.1.0.min.js contains a UTF-8 byte sequence that is not valid

Currently, I am attempting to implement the justgage plugin on my Rails 4 application. However, an error has arisen: raphael.2.1.0.min.js contains an invalid UTF-8 byte sequence The only changes I made to my application.js were: //= require justgage.1 ...

What is the best way to dynamically populate a table with JSON data that is received from an API response?

Currently, I have a table that contains the FORM element: <table id="example" class="sortable"> <caption><h3><strong>Product inventory list</strong></h3></caption> <thead> <tr ...

Protecting a javascript string in php: A comprehensive guide

Having trouble with my PHP javascript string. Attempted to add a string to a variable within a switch statement but encountered an error: $blocPub = '<script type="text/javascript"> var rdads=new String(Math.random()).substring (2, 11 ...