if the user only enters spaces into the input field, it triggers a validation error

31 Views Asked by At

I'm working on an Angular form where users can input their phone numbers. I've added a custom directive appPhoneExtMask for phone number formatting and applied Angular form validation for minlength and maxlength. However, I'm facing an issue where if the user only enters spaces into the input field, it triggers a validation error. I want the form to ignore or trim spaces before performing validation checks. Here is the code snippet for the input field:

i am expect get only number and ignore string value also count only number in minimum and maximum lenght

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; // Exit early if event is null
    }
    let newVal = event.replace(/\D/g, '');
    if (backspace && newVal.length <= 6) {
      newVal = newVal.substring(0, newVal.length - 1);
    }
    if (newVal.length === 0) {
      newVal = '';
    } else if (newVal.length <= 3) {
      newVal = newVal.replace(/^(\d{0,3})/, '$1');
    } else if (newVal.length <= 6) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '$1-$2');
    } else if (newVal.length == 10) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '$1-$2-$3');
    } else if (newVal.length <= 10) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '$1-$2-$3');
    } else if (newVal.length <= 20) {
      newVal = newVal.substring(0, 20);
      newVal = newVal.replace(
        /^(\d{0,3})(\d{0,3})(\d{0,4})(\d{0,5})/,
        '$1-$2-$3 x $4'
      );
    } else {
      if (newVal.length >= 12) {
        newVal = newVal.substring(0, 12);
        newVal = newVal.replace(
          /^(\d{0,3})(\d{0,3})(\d{0,4})(\d{0,5})/,
          '$1-$2-$3 x$4'
        );

      } else {
        newVal = newVal.substring(0, 12);
        newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '$1-$2-$3');
      }
    }
    this.ngControl.valueAccessor.writeValue(newVal);
    if (newVal.length == 12 || newVal.length == 20)
      this.ngControl.control.setErrors(null);
    else
      this.ngControl.control.setValidators([Validators.pattern(/^(1\s?)?(\d{3}|\(\d{3}\))[\s\-]?\d{3}[\s\-]?\d{4}( ?x([0-9]{3}))?$/)]);
  }
}
<input type="text" placeholder="Phone" class="form-control" formControlName="phone" minlength="12" maxlength="20" appPhoneExtMask [ngClass]="{ 'is-invalid': (isSaved && contactForm.get('phone').errors)}">

1

There are 1 best solutions below

0
Kuldip Baldaniya On

Use This Function

 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)">