Directive for masking input values

I am in need of an input that adheres to the following format:

[00-23]:[00-59]

Due to the limitations of Angular 2.4, where the pattern directive is unavailable and external libraries like primeNG cannot be used, I have been attempting to create a directive for this purpose:

@HostListener('keyup', ['$event']) onKeyUp(event) {
    var newVal = this.el.nativeElement.value.replace(/\D/g, '');
    var rawValue = newVal;
    
    // default format for empty value
    if(newVal.length === 0) {
        newVal = '00:00';
    } 
    // do not display colon for empty groups at the end
    else if(newVal.length === 1) {
        newVal = newVal.replace(/^(\d{1})/, '00:0$1');
    } else {
        newVal = newVal.replace(/^(\d{2})(\d{2})/, '$1:$2');
    }
    
    // set the new value
    this.el.nativeElement.value = newVal;
}

This implementation works as intended for the first two digits entered.

Initial string:

00:00

After pressing the number 1:

00:01

Subsequently pressing the number 2:

00:12

However, upon entering a third digit, the result is:

00:123

Instead of 01:23, and 00:1234 rather than 12:34

Despite this issue, backspacing functions correctly.

Is there a solution to this challenge that solely involves using a directive?

Answer №1

Give this a shot in your latest attempt:

replace(/^(\d{0,2})(\d{0,2})/g, '$1:$2')
. Hopefully, it does the trick.

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

Executing a series of imported functions from a TypeScript module

I'm developing a program that requires importing multiple functions from a separate file and executing them all to add their return values to an expected output or data transformation. It's part of a larger project where I need these functions to ...

In PHP, implement a function to insert a delimiter into a string retrieved from a

Merchant Id|Merchant|Website|Transaction In Period|Voids In Period|Gross Sales Amount|Total Commision in Period 9766|Mountains Plus Outdoor Gear|www.MPGear.com|1|0|88.91|8.89 12447|Meritline.com|www.meritline.com|5|0|52.86|3.71 16213|East Coas ...

Search MongoDB using regular expressions that disregard any punctuation marks

I'm currently working on querying a MongoDB collection to find a single item based on a string property using react-router-dom's NavLink. The challenge arises when the prop via NavLink contains hyphens instead of spaces, and there are also names ...

Testing the open dialog with a unit test case

I encountered an issue while writing a unit test case for the open dialog feature in Angular 7. A TypeError is being thrown: "Cannot read property 'debugElement' of undefined." I am seeking assistance from anyone who can help me troubleshoot this ...

Unable to locate the "fcm-node" module in Node.js with TypeScript

When working on a TypeScript project, I usually rely on the fcm-node package to send Firebase push notifications in Node.js. However, this time around, I faced an issue. I know that for TypeScript projects, we also need to install type definitions (@types ...

Discover the second character in the sequence and substitute it with a different numeral

I need to manipulate a string where I want to replace the second digit with a random number. The challenge lies in identifying the second digit and performing the replacement. How can I accomplish this task? 1. "data[KPI][0][rows][0][name]" 2. "data[KPI][ ...

Pattern for either one or two digits with an optional decimal point in regular expressions

Currently, I'm utilizing for input masking. I am specifically focusing on the "patterns" option and encountering difficulties while trying to create a regex expression for capturing 1 or 2 digits with an optional decimal place. Acceptable inputs: ...

The specified dependency, * core-js/fn/symbol, could not be located

I am in the process of developing a Vue.js application with Vuex and have encountered some errors during the build. I attempted to resolve the issue by installing npm install --save core-js/fn/symbol, but unfortunately, it did not work as expected. https:/ ...

Running a TypeScript file on Heroku Scheduler - A step-by-step guide

I have set up a TypeScript server on Heroku and am attempting to schedule a recurring job to run hourly. The application itself functions smoothly and serves all the necessary data, but I encounter failures when trying to execute a job using "Heroku Schedu ...

NextJs Route Groups are causing issues as they do not properly exclude themselves from the app's layout.tsx

As far as I know, the layout.tsx in the app directory serves as the root layout. To customize the layout structure for specific segments, you can use Route Groups. More information can be found here. In this setup, any page.tsx file inside a directory nam ...

The datatable only accepts arrays and Iterable data types

While attempting to perform a CRUD operation with the datatable, I encountered an error message "Only arrays and iterables are allowed in datatable" upon clicking the submit button for creation. The console pointed out the error in the component.html file ...

Utilizing the namespace importation method correctly

How can I efficiently utilize classes from a namespace that may be the same or different from the current file's namespace? I currently have the following two files. TypeA.ts: export namespace Game { @ccclass export class TypeA extends cc.Component ...

Having trouble sending an image to the API endpoint using Angular 6 reactive form

Currently utilizing Angular 6 along with Reactive Form The task at hand involves uploading a user avatar image, which led to the creation of a change-avatar component containing the code provided below. import {Component, OnInit, ViewChild} from '@a ...

Navigating with the Angular router and then triggering a reload

Is there a way to reload the app after navigating to a specific route? I am currently using router.navigate to direct users to different routes based on their roles. It's working fine, but I need to reload the page after routing when coming from the ...

`The Art of Curved Arrows in sigjma.js, typescript, and npm`

I have encountered an issue while trying to draw curved arrows in sigma.js within my TypeScript npm project. The error occurs on the browser/client-side: Uncaught TypeError: Cannot read properties of undefined (reading 'process') at Sigma.pro ...

A guide on updating URLs that are not enclosed within an anchor tag using JavaScript

In my current scenario, I am dealing with text that includes URL links presented in two different formats. www.stackoverflow.com <a href="http://www.stackoverflow.com">Stack over flow</a> My objective is to create a straightforward function ...

Typescript: Retrieve an interface containing properties that are found in interface A, but not in interface B

I am currently developing a mapper that will facilitate the translation between a serialized entity state and a form state. In the context of two given interfaces A and B, I am exploring ways to derive a third interface C that includes properties present ...

Conceal components using routing in Angular2 release candidate 1

I have a request regarding certain elements that are to be displayed on all pages except the login page. I am considering using either ngIf or the hidden property of the elements to hide them when the user is on the login page. Here is what I have attempt ...

Is there a Selenium regex specific to trademarks that can be used in

Just diving into the world of regex and selenium, I need to verify the presence of a text like this: © Negurici 2012. All rights reserved. Email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="29474c4e5c5b404a40694e4448404507 ...

What causes the createResource error to become undefined when it is refetched before being properly set?

How can I access and display the error property for a createResource? In this scenario, why is the error initially set to undefined before it is thrown? The logging shows that it first displays undefined for the error before eventually getting to line er ...