Should the input field only contain spaces, a validation error will be triggered by the user

I am currently working on an Angular form implementation that allows users to enter their phone numbers. I have integrated a custom directive called appPhoneExtMask for formatting the phone numbers and have also implemented Angular form validation for both minlength and maxlength. However, I am facing an issue where the input field triggers a validation error if the user only inputs spaces. I would like the form to either ignore or trim any spaces before conducting the validation checks. Below is the snippet of code pertaining to the input field:

My expectation is to receive only numerical input, disregard any string values, and ensure that the length falls within the specified minimum and maximum range.

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

@Directive({
  selector: '[formControlName][appPhoneExtMask]',
})
export class PhoneExtentionMaskDirective {
  constructor(public ngControl: NgControl) {}

  @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    this.onInputChange(event, false);
  }

  @HostListener('keydown.backspace', ['$event'])
  keydownBackspace(event) {
    this.onInputChange(this.ngControl.control.value, true);
  }

  ngOnInit() {
    this.formatValue(this.ngControl.control.value, false);
  }

  onInputChange(event, backspace) {
    this.formatValue(event, backspace);
  }

  formatValue(event, backspace) {
    if (event === null) {
      return; 
    }
    let newVal = event.replace(/\D/g, '');
    if (backspace && newVal.length <= 6) {
      newVal = newVal.substring(0, newVal.length - 1);
    }
    // Remaining code block unchanged for brevity...
<input type="text" placeholder="Phone" class="form-control" formControlName="phone" minlength="12" maxlength="20" appPhoneExtMask [ngClass]="{ 'is-invalid': (isSaved && contactForm.get('phone').errors)}">

Answer №1

Utilize This Method

 handleSpaceKey(event: KeyboardEvent) {
    // Check if the pressed key is space
    if (event.key === ' ' || event.code === 'Space') {
      // Check if the current value of the input field is only spaces
      if ((event.target as HTMLInputElement).value.trim() === '') {
        // Prevent default behavior (typing space) if only spaces are present
        event.preventDefault();
      }
    }
  }
<input type="text" placeholder="Phone" class="form-control" formControlName="phone"  minlength="12" maxlength="20"
                                appPhoneExtMask [ngClass]="{ 'is-invalid': (isSaved && contactForm.phone.errors)}" (keydown)="handleSpaceKey($event)">

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

Creating a unique ngrx operator from scratch that modifies the source observable and outputs its type

I developed a custom operator called waitFor that is being used in my effects like this: public effect$: Observable<Action> = createEffect(() => { return this.actions$.pipe( ofType(myAction), waitFor<ReturnType<typeof myActio ...

Tips for writing unit tests for clipboard copy functionality in an Angular application

How can we monitor the behavior of the clipboard.copy method? For const clipboard = TestBed.inject(Clipboard); spyOn(clipboard, 'copy').and.returnValue(true); An error warning pops up indicating that Argument of type '"copy"' ...

Reorganizing Firebase data in Ionic 2

I am currently working on an exciting project to develop an Ionic notes application, where users can easily rearrange items in the list using the reorderArray() function. However, I encountered an issue with Firebase resulting in an error message related t ...

Looking for a way to validate all form fields even when only one field is being used?

In Angular 8, I am facing an issue where the current validation only checks the field being modified. However, there are some fields whose validation depends on the values of other fields. Is there a way to make Angular recheck all fields for validation? ...

Unable to locate module src/ in Node.js TypeScript

I'm encountering issues with non-relative imports in my node.js / typescript application. Here is my tsconfig: { "compilerOptions": { "target": "es6", "module": "commonjs", "lib": ["dom", "es6", "es2017", "esnext.asynciterable"], "s ...

What is the best way to access an optional field in Typescript without causing errors?

Is there a way to dereference an optional field from an interface in the following scenario? interface Sample { key1?: Array<Obj1> } interface Obj1 { a?: Obj2; } interface Obj2 { b?: string; } const a: Sample["key1"][number][" ...

Transferring Complex Data Structures from the Realtime Database to Firestore

I am currently in the process of migrating data from Firebase Realtime Database to Firestore, specifically dealing with nested data that I would like to organize into a collection. For example: "data" : { "-LYBzlXPoN0137KRLovk" : { "-LYC-HHqDFgL9Po ...

The act of exporting an enum from a user-defined TypeScript path leads to the error message "Module not

I have set up a custom path as explained in this particular discussion. "baseUrl": ".", "paths": { "@library/*": [ "./src/myFolder/*" ], } Within this module, I am exporting an Enum. export enum EN ...

A method to access a stored value in localStorage that does not involve utilizing the __zone_symbol__value property

I am encountering a problem with localStorage. After storing user information in localStorage, I am unable to retrieve it without using the __zone_symbol__value property of the parsed value. This is how I store data into locaStorage localStorage.setItem(& ...

Angular firing a function in the then clause before the initial function is executed

I have a situation where I need to make multiple service calls simultaneously, but there is one call that must be completed before the others are triggered. I have set it up so that the other calls should only happen after the .then(function() {}) block of ...

Is it possible to retrieve data from a promise using the `use` hook within a context?

Scenario In my application, I have a component called UserContext which handles the authentication process. This is how the code for UserProvider looks: const UserProvider = ({ children }: { children: React.ReactNode }) => { const [user, setUser] = ...

Using Typescript to configure a custom proxy in a Create React App

I am looking to implement request proxying from a Create React App to a separate API server, with the ability to set the server dynamically or using environment variables. While I have followed the guide on manually configuring the proxy, I am encounteri ...

What steps do I need to take in order to set up InfluxDB with Nest

As a beginner in the world of software development, I am eager to expand my knowledge and skills. Has anyone had experience operating influxdb with nestjs? If so, I would greatly appreciate it if you could share your past experiences. Thank you for takin ...

Functionality for communicating components is only operational on a single platform

I am looking to create a service that can notify my components when there are any changes to the 'idCustomer' property. These changes should trigger certain actions in different components. Currently, I am using console.log to check if the change ...

Trigger the Material UI DatePicker to open upon clicking the input field

I have a component that is not receiving the onClick event. I understand that I need to pass a prop with open as a boolean value, but I'm struggling to find a way to trigger it when clicking on MuiDatePicker. Here is an image to show where I want to ...

Ensuring child input components are validated upon submission using Vee-Validate and Vue.js 2

Currently, I am working on creating a Registration form with multiple "Input Field" components that require validation once the Submit button is pressed. While each input field validates individually when the text is changed, I am struggling to implement a ...

Exploring Angular's powerful routing feature: lazy loading modules with loadChildren

I am developing an Ionic app that includes tabs and a login page. The tabs are structured in their own module with a routing module for each tab. Upon launching the app, I want users to be directed to the login page first. After successfully logging in, ...

Understanding Angular's Scoping Challenges

I have a function that retrieves an array and assigns it to this.usStates. main(){ this.addressService.getState().subscribe( (data:any)=>{ this.usStates = data; if(this.usStates.length===0) { this.notificationServic ...

Learn how to subscribe to Azure Event Grid using Angular without the need for a backend service layer

I am currently working on an Angular project and I am looking to set up Azure Event Grid subscription directly from the client-side without the need for a backend service. After exploring different options, I have not yet found a straightforward solution. ...