What is the best way to create a directive that limits the characters entered into a text box based on a specific regex pattern?

I am trying to use a regex pattern [a-z] in my directive to only allow lowercase alphabets. However, I want the directive to prevent any other characters from being typed into the input field. Despite going through the documentation, I am struggling to implement this functionality.

Answer №1

I have modified an existing plunker to meet your specific requirements.

This directive is a sample of what it may look like:

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

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

  constructor(private el: ElementRef) { }

  @Input() OnlyLowerCaseAlphabets: boolean;

  private regex: RegExp = new RegExp( /^[a-z]+$/);

  @HostListener('keydown', [ '$event' ])
  onKeyDown(event: KeyboardEvent) {

    let current: string = this.el.nativeElement.value;
  
    let next: string = current.concat(event.key);
    if (next && !String(next).match(this.regex)) {
        event.preventDefault();
    }
   }

}

You can view the modified plunker here:

https://embed.plnkr.co/M6gYgSxeuw7wW6rfoWEZ/

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

Best type for an array of dictionaries

Is there a way to correctly assign the variable r without utilizing any? const d = [{ result: 'aEzRuMA6AtQ6KAql8W9V' }, { result: 'N6mkKsnFJj98MHtYMxIi' }] const result = d.map((r: HERE) => r.result) console.log(result ) // will pr ...

Running NG BUILD from Gulp can be done using either child-process.spawn or by disabling all output in child-process.exec

Have you come across a similar question like this Call "ng build" from inside a gulp task? I have found a way to successfully build Angular using Gulp in order to prevent overflowing the output buffer. Here's how I achieved it: const child ...

Exploring the Incorporation of String as a Component Identifier in React and TypeScript

My input component can render either a textarea component (from a library) or a regular input. Check out the code below: import React, { useEffect, useRef, useState } from 'react' import './AppInput.css' interface Props { placehold ...

Unable to finish the real-time search request

Coding Challenge <form [formGroup]="searchForm" onsubmit="return false" id="searchField" ng-submit="" \"> <input type="text" placeholder="Search" formControlName="search" (keyup)="updateQuery()"/> <li *ngFor="let product o ...

Fulfill the specified amounts for each row within a collection of items

I have an array of objects containing quantities. Each object includes a key indicating the amount to fill (amountToFill) and another key representing the already filled amount (amountFilled). The goal is to specify a quantity (amount: number = 50;) and au ...

Another option to avoid using complicated else if chains

I'm facing a challenge with a function that returns a value known as user_id. It involves multiple conditions that need to be checked. First condition: Verify the service variable Second condition: If not found, retrieve user_id from local storage ...

Stop express.js from transmitting angular client code until login is completed

I currently have a website built with Mean.io and I am seeking a way to protect my angular client code from being accessed by users without proper login credentials. As it stands, anyone who has my website URL can view all of the angular code, which is s ...

Transferring objects between components using Angular 9's router

Currently, I am utilizing the most recent versions of Angular 9 and Node.js. Below, you will find a snippet of the code: Extracted from app.component <router-outlet></router-outlet> Extracted from app.component.ts import { Component, OnInit ...

Ways to retrieve "this" while utilizing a service for handling HTTP response errors

I have a basic notification system in place: @Injectable({ providedIn: 'root', }) export class NotificationService { constructor(private snackBar: MatSnackBar) {} public showNotification(message: string, style: string = 'success' ...

Obtaining the count of a specific column in Angular 6 by grouping objects based on the same value in an array

In TypeScript, I have an array of objects and I am using a foreach loop. The array contains 2 columns with a progress value of 100, while the rest have values less than 100. My goal is to calculate the count of columns with a progress value of 100, which ...

Incorporate a stylish gradient background into react-chartjs-2

I am currently working on adding a gradient background with some transparency to a radar graph within a react component. So far, I have only found solutions that involve referencing a chartjs canvas in an html file, but none for implementing it directly in ...

The ngx-material-timepicker lacks proper design when the minutesGap is set to 1

https://i.sstatic.net/J4z5H.png Check out this example of HTML code I have written: <mat-form-field> <mat-label>StartTime</mat-label> <input matInput readonly [ngxTimepicker]="timeStart" [formControlName]="'sta ...

I have successfully retrieved websocket data in my Angular service, but I am encountering an issue where it is

I am facing an issue while trying to transmit data from my go_backend to my angular frontend. The problem I encountered is as follows: Although the websocket connection is established and I can see the data inside my Service, when I attempt to subscribe t ...

Transforming a JavaScript chained setter into TypeScript

I have been utilizing this idiom in JavaScript to facilitate the creation of chained setters. function bar() { let p = 0; function f() { } f.prop = function(d) { return !arguments.length ? p : (p = d, f); } return f; } ...

The combination of React Vite and SockJS Client has encountered a failure in all transport

My current project is utilizing react + vite without any proxy configuration. I am attempting to use webstomp-client and sockjs to establish a connection with a websocket server that is supported by Springboot using SockJS. The backend Springboot server w ...

Providing properties to the main Vue.js components

An Issue I'm Facing I am currently attempting to pass a prop to my root constructor. To achieve this, I have been exploring the use of propsData, which I learned about from this resource: var appComponent = Vue.component('app', require(&ap ...

Tailored validation for targeted field

How can I validate a partial form based on requirements? Built with Angular 7 and Clarity I have a form using the clrForm component that includes: Field 1: Name Field 2: URL Field 3: Date The form also has two buttons: Button 1: Verify Button 2: Su ...

Issue encountered while implementing a recursive type within a function

I've created a type that recursively extracts indices from nested objects and organizes them into a flat, strongly-typed tuple as shown below: type NestedRecord = Record<string, any> type RecursiveGetIndex< TRecord extends NestedRecord, ...

Confirm the creation of a data-bound component using unit testing with Angular and Jasmine

Check out this snippet of code... Unit Test: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { AppComponent } from './search ...

What is causing the element to disappear in this basic Angular Material Sidenav component when using css border-radius? Check out the demo to see the issue in action

I have a question regarding the Angular Material Sidenav component. I noticed that in the code below, when I increase the border-radius property to a certain value, the element seems to disappear. <mat-drawer-container class="example-container" ...