AngularJS -> Choice for specifying user's decimal format and limit restrictions

Is there a way to use AngularJS to dynamically limit user input to numbers between 0 and 1 with hundredths? For instance, if a user types 0, it should be converted to 0.00; if they type 1, it should become 1.00. I already have a JavaScript function for limiting user input, but I would like to make it dynamic with AngularJS.

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

myApp.controller('CalcCtrl', function ($scope) {
    var num = 0.0;
    $scope.qty = new Quantity();
    $scope.num = num;
  });

function Quantity(numOfPcs) {
    var qty = numOfPcs;

    this.__defineGetter__("qty", function () {
        return qty;
    });

    this.__defineSetter__("qty", function (val) {        
        val = parseFloat(val);
        qty = val;
    });

}

http://jsfiddle.net/xnehel/ur26k9cx/6/

Answer №1

To implement field validation for restricting user input, consider using a custom directive or a library like ui-mask. You can check out an example in this plunkr demo.

<form name="priceForm" novalidate>
  <label>Input currency</label>
  <input type="text" name="price" ng-model="price" ng-pattern="/^\d+[\.]\d{2}$/i" />
  <div ng-show="priceForm.price.$error.pattern">Invalid price</div>
</form>

If you require strict input matching based on a specific pattern, consider creating a custom directive or utilizing a library like ui-mask to achieve this functionality.

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

Filtering data from Arduino using web serial communication

My setup consists of an Arduino kit connected to a webserial API that sends data to an HTML div identified by the id 'target'. Currently, all the data is being logged into one stream despite having multiple dials and switches on the Arduino. Th ...

What are the steps involved in manipulating objects within an asynchronous result object?

I'm interested in learning how to manipulate a JS object from one file into another asynchronously, as my experience with asynchronous code principles is limited. Scenario: In my app.js file, I dynamically generate 'app panels' based on ...

Looking to enhance code readability using regular expressions

While I am not a programmer, I enjoy exploring and learning new things. Here is what I have: 1) My URL is structured like this: http://site.com/#!/show/me/stuff/1-12/ 2) I have a jQuery pagination script that displays the number of available pages. Each ...

Secure API Calls with Prismic while Keeping Access Tokens Hidden

As I delve into the world of building a Vue.js web app, I find myself faced with the challenge of making calls to my Prismic repository without exposing my access token. The Rest API approach outlined here seems promising, but I'm at a loss on how to ...

AngularJS: How to handle promise returned by 'Collector' service in order to pass value within function?

My Collector service is designed to manage models by interacting with localStorage and the server. The function Collector.retrieveModel(uuid) retrieves a model from the collector, first checking if it exists in localStorage, then requesting it from the ser ...

Extract content from an HTML form within a specific cell using Cheerio

A sample HTML table is displayed below: <tr class="row-class" role="row"> <td>Text1</td> <td> <form method='get' action='http://example.php'> <input type='hidden' ...

The Mystery of jQuery Isotope Plugin: Why Can't I Add "display:none" Inline?

I'm currently in the process of integrating Isotope into my latest Wordpress theme. However, I've encountered an issue where it's not appearing on the page due to some external factor adding an inline style (display:none) to the main isotope ...

Traversing through objects in react.js

Hello there, I'm currently learning React and JavaScript but facing some challenges with a particular task. Let's dive into it! So, imagine I have an array like this: clients = ["Alex", "Jimmy"] and then I proceed to create another array using th ...

AWS Lambda Error: Module not found - please check the file path '/var/task/index'

Node.js Alexa Task Problem Presently, I am working on creating a Node.js Alexa Skill using AWS Lambda. One of the functions I am struggling with involves fetching data from the OpenWeather API and storing it in a variable named weather. Below is the relev ...

Struggling to access values from your model using EL in JavaScript? Let me provide some guidance

In my model, there is an object named "domain" with two methods: getDescriptionEn() and getDescriptionFr(). I am trying to retrieve the appropriate description based on the current locale. My issue lies in the following code snippet: var locale = "${cur ...

Ways to move information from one controller to another

I'm currently working on transferring data between controllers. In my initial controller, I use the following code to fetch data when the page loads via HTTP- function FetchDataController($scope, $http) { $http.defaults.useXDomain = true; $ ...

Steps to display a div on top of a background image

Here is a visual representation of my design for better understanding: I am currently working on developing the central content that overlays the image. However, when I insert divs with background colors into my HTML to test their placement, I do not see ...

Understanding the Typescript Type for a JSON Schema Object

When working with JSON-schema objects in typescript, is there a specific type that should be associated with them? I currently have a method within my class that validates whether its members adhere to the dynamic json schema schema. This is how I am doing ...

Directives causing disruption to one another

Two directives are at the same level in my code: function signUpForm(djangoAuth, Validate){ return{ restrict:'A', controller:["$rootScope","$scope",function($rootScope, $scope){ $scope.submitFunction = function(formData){ ...

Guide on how to update the controller value in AngularJS directive to trigger data retrieval

I currently have multiple controllers responsible for fetching data from the server. One example of such a controller is shown below: var vm = this; var month = 1; loadStatusCount(); function loadStatusCount() { vm.summaryCount = [] ...

Conceal the form node's visibility upon initial inspection

My goal is to understand how the "add a comment" feature on Stack Overflow works by examining the code in three sections: footnote-list, footnote-form, and add-form-link. footnote-list footnote-form add-form-link <div class="col-md-12 footnotes"> ...

What causes the transformation of [{"value":"tag1"} into [object Object] when it is logged?

Currently on my node.js server, the code I'm using is as follows: var tags = [{"value":"tag1"},{"value":"tag2"}]; console.log("tags: " + tags); My expectation was to see this in the console: tags: [{"value":"tag1"},{"value":"tag2"}] However, what ...

Click to dynamically toggle classes with jQuery

I am trying to apply a class called 'select' when I click on a paragraph tag. However, the code I have written doesn't seem to be working. Can someone please provide some suggestions? Here is the code: <style type="text/css"> #el ...

Step-by-step guide on generating an index through mongoose and elastic search in a node.js and express.js environment

I am looking to set up the index in elastic search using mongoose and express, but I have not been able to find any documentation on how to do it. I attempted to use mongoosastic, but it did not meet my needs. Is there anyone who can assist me with this? ...

Vanilla JavaScript Troubleshooting: Top Scroll Button Issue

Attempting to develop a Scroll To Top Button utilizing Vanilla JS, encountering errors in the dev console. Existing jQuery code that needs conversion to vanilla js Uncaught TypeError: Cannot read property 'addEventListener' of null My Vanilla ...