Angular: Implementing number field validation with a custom directive

I am currently developing a directive to validate an input:number field. The main objective of this field is to only accept numbers between 0-9 or a decimal number with up to 3 decimal places (ensuring that all numbers are positive without any symbols).

Since there are over 30 similar fields, I decided to create a directive to restrict users from entering unnecessary characters.

Below you will find the code for the directive as well as a Stackblitz example:

Directive:

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[validTestValue]'
})
export class NumberDirective {

  @HostListener('keydown', ['$event'])
  @HostListener('input', ['$event'])
  onKeyDown(e) {
    const key = ['Backspace', 'Delete', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.'];
    let check = key.includes(e.key) && /^\d{1,7}((.)|(.\d{0,3})?)$/.test(e.target.value);
    console.log(check)
    if (!check) {
      e.preventDefault();
    }
  }
}

HTML:

<input type="number" validTestValue class="testInput-field text-center" />
<!--These input fields are repeated multiple times throughout my code-->

The issue with the current code is that while it does allow only digits and decimal points, there are other problems arising such as:

  1. The maximum allowed length should be 7 digits, regardless of whether it is a decimal number. For instance: 1, 12, 1234567
  2. If it is a decimal number, then the maximum length should be 7 digits before the decimal and 3 digits after. For example: 1, 1.2, 1.12, 1.123
  3. It should not allow Backspacing (once limit reached) or moving the cursor.
  4. If the field is left blank without a default value

Answer №1

It seems like the problem lies within your regular expression (regex)

/^\d{1,7}((.)|(.\d{0,3})?)

This regex pattern allows for 1 to 7 digits ({1,7} matches the preceding token between 1 and 7 times, as many times as possible)

Currently, this is the pattern I am utilizing. It assists in restricting the number of decimal points allowed in a field

Check out this numbers-only directive for more information

Usage in the template file:

<input type="text" numbers-only="2" placeholder=""

Answer №2

According to the approach suggested by Dilshan, it will only verify the number of digits after the decimal point and does not consider validating spaces based on his regular expression. I have made some modifications to Dilshan's solution in order to align with your requirements as per my interpretation.

REGEX:

^([\d]{0,7})((\.{1})([\d]{1,3})?)?$

HTML:

<input type="text" validateNumber="7.3" />

You can find the reference implementation on Stackblitz.

I hope this solution is beneficial for you 😊.

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

Unable to showcase drop-down menu as ajax output on WordPress platform

I am facing an issue with displaying the output of two drop-down boxes - one with custom taxonomy and the other with its custom post under the currently selected taxonomy. To address this, I have implemented an on-change function. However, the output is no ...

expand attribute of foundational interface

My current situation is as follows: interface A { x: { f1(s: string): string; }; } interface B extends A { } I am looking to enhance interface A by adding a new method called f2 within the context of interface B, without redefining f1. It would ...

Ajax is incapable of achieving success or encountering failure

I'm having some trouble displaying search results on the view using AJAX. The action retrieves JSON data and sends it, but for some reason the AJAX call is not receiving the data. $(function () { $("#btnSearchForUser").click(function () { ...

The functionality of the Array.sort method is known to cease functioning when the length of the Array exceeds

I have been working on a hybrid application that combines Angular and Ionic's framework. Recently, I discovered an issue with one of my functions not functioning as expected. Within my app, users are able to create a database of items stored as objec ...

Scroll upwards within a nested div

Is there a way to smoothly animate the content of the inner div upward without requiring any button clicks? Also, is there a method to trigger an event once the animation has completed? ...

Press the list item corresponding to a specific name by utilizing JavaScript in Selenium with Python

I am currently developing a web form and facing a challenge with clicking on a specific li within a ul based on the text of the list item. For example, in the scenario below, I need to click on the option labeled "Your Employer". While I have successfully ...

What will be the output of this typescript function?

Whenever I hover over the keyword 'function', this cryptic description pops up: "(local function)(this: any, next: (err?: mongoose.CallbackError | undefined) => void): Promise<void>" I'm confused about whether it return ...

Is there a different method to retrieve language bundles with next-i18next instead of using a customized Node server?

Currently, I am developing a Next.js application that will utilize i18next translations organized in the recommended file structure for bundles. For example: static/locales/en/common.js static/locales/de/common.js You can refer to this article: https://m ...

Icon displayed within the input field

Is there a simple method to add an input text element with a clear icon on the right side, similar to the layout of the Google search box? I've searched, but I could only find instructions for placing an icon as the background of the input element. I ...

Why does Chrome keep retrieving an outdated JavaScript file?

Lately, I've been facing a frustrating issue that I just can't seem to figure out. Every now and then, when I update the JavaScript or CSS files for my website hosted on Siteground, Chrome simply refuses to acknowledge the changes. While other br ...

Regular intervals and asynchronous JavaScript and XML (AJAX) requests are

There is a simple chat tool in place to ensure the chat room stays updated: setInterval (loadLog, 2500); function loadLog(){ //Scroll height prior to the request var oldScrollHeight = document.getElementById("chatMessages").scrollHeight - 20; ...

What is the best way to verify the relationship between parent and children nodes in a tree structure?

Check out my Plnkr with nested loops of checkboxes: here Below is the HTML code for the nested loops of checkboxes: <ul> <li ng-repeat="continent in destinations"> <input type="checkbox" ng-model="continent.selected"> {{contin ...

Executing a quick shallow copy of an object in a single ReactJS operation

I have an object in a component that I need to copy to a property. Currently, I am achieving this as follows: onSubmit: values => { data.label = values.label; data.userName = values.userName; data.recipientUserName = values.recipient ...

Guide to testing an Angular Component with TranslateTestingModule.withTranslations() employing MockBuilder (from ng-mocks)

Currently, I am utilizing ng-mocks to test an Angular component that incorporates translations. My goal is to utilize the .withTranslation function in order to adhere to the language file structure. However, I have been unable to figure out how to leverage ...

What is the best way to include thousand separators in a numeric array with the data retrieved from a server?

Is there a way to automatically add thousand separators to numbers in an array that are in the thousands? Here is an example JSON object: { "message": "Successfully data has been fetched.", "success": true, "data": { "dataHeaders": [ "1", ...

Angular 6: Issues with API Get Method not executing when an integer value is passed with an empty string

I'm experiencing an issue in my angular application when trying to call an API method from angular. The method requires two parameters - one integer value and one string value, which is optional. Below is the code snippet in Typescript: let id:numbe ...

The promise object is displayed instead of the actual data retrieved from the API call

I am currently working on fetching data from an API and showcasing the name of the returned data on the front end. This function successfully retrieves the data through an API call: async function retrieveData(url){ var _data; let response = await fetch( ...

asp gridview Export

I have a javascript function below that is currently functioning. I made a modification to the code (from examples found online): WinPrint.document.write(printContent.outerHTML); Initially, I used innerhtml but the grid formatting was not correct. Howeve ...

Encountering a glitch in Django Templates while trying to use the event.preventDefault() method

I have created a Django website where if the product has a field with is_active = False, it will be removed from the basket in the shop. Here is the script I wrote in an HTML file: {% if table.is_active %} <div data-index="{{ t ...

Express: ERROR_HTTP_HEADERS_ALREADY_SENT - It is not possible to set headers once they have already been sent to the client

After reviewing numerous discussions on the same topic, I am struggling to identify where I might be sending the headers initially. The stack trace provided indicates the following: It is concerning that I receive a 204 as it successfully adds to the data ...