如果用户仅在输入字段中输入空格,则会触发验证错误

问题描述 投票:0回答:1

我正在开发一个 Angular 表单,用户可以在其中输入他们的电话号码。我添加了一个自定义指令 appPhoneExtMask 用于电话号码格式设置,并对 minlength 和 maxlength 应用了 Angular 表单验证。但是,我面临一个问题,如果用户仅在输入字段中输入空格,则会触发验证错误。我希望表单在执行验证检查之前忽略或修剪空格。这是输入字段的代码片段:

我期望只获取数字并忽略字符串值也只计算最小和最大长度中的数字

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

angular typescript validation angular-forms
1个回答
0
投票

使用此功能

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

© www.soinside.com 2019 - 2024. All rights reserved.