首页 > 解决方案 > 用于验证电话号码的 Angular 表单验证

问题描述

我正在尝试使用正则表达式以角度验证电话号码

HTML 内容

<div class="form-group row">
                <input type="text" class="form-control" appPhoneMask placeholder="Mobile Number" autocomplete="off"
                    [ngClass]="{ 'is-invalid': (f.inputCountryCode.errors && mobileNumberform.submitted) }"
                    formControlName="inputCountryCode">
                <div *ngIf="(f.inputCountryCode.invalid ) || (f.inputCountryCode.invalid && (f.inputCountryCode.dirty || f.inputCountryCode.touched))"
                    class="invalid-feedback">
                    <div *ngIf="f.inputCountryCode.errors.required">This field is required.</div>
                    <div *ngIf="f.inputCountryCode.errors.pattern">Invalid phone number.</div>
                </div>
            </div>

TS代码

 this.$form = this.$builder.group({
      selectCountryCode: [null, Validators.required],
      inputCountryCode: [null, [Validators.required, Validators.pattern("[0-9 ]{12}")]]
    });

验证模式应该允许带空格的数字号码,因为我使用的是电话号码掩码,它在 3 位数字后添加空格。

在此处输入图像描述

该模式不起作用,让电话号码验证错误

Angular 4手机号码验证

允许数字和空格的字段的正则表达式

屏蔽指令

export class PhoneMaskDirective {

  constructor(public ngControl: NgControl) { }

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

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


  onInputChange(event, backspace) {
    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 <= 9) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '$1 $2 $3');
    } else {
      newVal = newVal.substring(0, 10);
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '$1 $2 $3');
    }
    this.ngControl.valueAccessor.writeValue(newVal);
  }
}

标签: javascriptangularangular7angular8angular-validation

解决方案


您可以允许:

  • 9999 9999
  • +61 2 9999 9999
  • (02) 9999 9999
Validators.pattern('[- +()0-9]+')

推荐阅读