【问题标题】:Angular form validation to validate the phone number用于验证电话号码的 Angular 表单验证
【发布时间】:2020-03-26 16:33:43
【问题描述】:

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

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 Mobile number validation

Regex for field that allows numbers and spaces

屏蔽指令

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

【问题讨论】:

  • 你在使用响应式表单吗?
  • 是的,我正在使用响应式表单
  • 正则表达式尝试匹配进行中的令牌 [0-9] 的 12 个字符,但您只输入了 11 个字符,因此会出错
  • 是的,我使用的是同一个,但我删除了括号和连字符并尝试进行电话号码验证

标签: javascript angular angular7 angular8 angular-validation


【解决方案1】:

您的正则表达式需要 12 个 [0-9 ] 符号,而您输入的仅包含 11 个。

inputCountryCode 的正则表达式更新为"[0-9 ]{11}"

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

或者你可以在输入的电话号码后面加一个空格,这样就变成了12个符号。

但我更愿意对电话号码使用更具体的正则表达式,例如'[0-9]{3} [0-9]{3} [0-9]{3}',因为您的模式电话号码11 1111 111 111111 是有效号码

【讨论】:

  • 那行不通。我已经添加了屏蔽代码你能告诉我我在哪里犯了错误
  • 您刚刚分享了来自here 的示例代码。所以这个指令是对的。确保您在 html 中正确使用它,还要检查 html 中表单字段的命名以及如何填写表单
  • 我也更新了 HTML 内容,HTML 内容与表单名称和控件都很好。还有其他问题,我无法弄清楚
【解决方案2】:

问题在于

Validators.pattern("[0-9 ]{12}")

替换为

Validators.pattern(new RegExp("[0-9 ]{12}"))

更改代码

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

【讨论】:

    【解决方案3】:

    你可以使用

    Validators.pattern("(09)[0-9 ]{9}")
    

    示例:09112223333

    条件: number 必须以 '09' 开头,应该是数字和固定长度(在此示例中为 11 位)

    【讨论】:

      【解决方案4】:

      您可以允许:

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

      【讨论】:

      • 谢谢! Validators.pattern('[- +()0-9]{6,}') 如果您希望至少有 6 个字符。
      【解决方案5】:

      另一个想法,类似地,您实际上可以强制输入值以保持电话格式,这是美国格式 123-123-1234 的示例。首先我们限制用户只输入数字:

      //Number formatting in your .ts file
        public numbersOnlyValidator(event: any) {
          const pattern = /^[0-9\-]*$/;
          if (!pattern.test(event.target.value)) {
            event.target.value = event.target.value.replace(/[^0-9\-]/g, "");
          }
        }
      

      然后,我们在 html 中添加带有指令 phoneMask 的电话字段:

       <div class="form-group row">
                 <input 
                   type="text" 
                   placeholder="phone number xxx-xxx-xxxx" 
                   class="form-control" 
                   id="phone" 
                   name="phone" 
                   maxlength="12"
                  [(ngModel)]="phone" 
                  phoneMask
                  [ngClass]="{ 'is-invalid': phone.touched || form.submitted && phone.invalid }"
                  #phone="ngModel" 
                  phoneMask 
                  (input)="numbersOnlyValidator($event)" />
      
                  <div *ngIf="(phone.touched || form.submitted) &&
                      phone.invalid" class="invalid-feedback">
                        <div *ngIf="phone.errors">
                          Please enter valid phone number.
                        </div>
                      </div>
       </div>
      

      这里你只过滤数字(input)="numbersOnlyValidator($event)"

      这是 html 中使用的指令 phoneMask,您实际上将输入格式化为虚线模式 NNN-NNN-NNNN:

      import { Directive, HostListener } from '@angular/core';
      
      @Directive({
        selector: '[phoneMask]'
      })
      export class PhoneMasksDirective {
      
        constructor() { }
      
        @HostListener('input', ['$event'])
        onKeyDown(event: KeyboardEvent) {
          const input = event.target as HTMLInputElement;
          let trimmed = input.value.replace(/\s+/g, '');
      
          if (trimmed.length > 12) {
            trimmed = trimmed.substr(0, 12);
          }
       
          trimmed = trimmed.replace(/-/g,'');
      
          let numbers = [];
          numbers.push(trimmed.substr(0,3));
          if(trimmed.substr(3,3)!=="")
          numbers.push(trimmed.substr(3,3));
          if(trimmed.substr(6,4)!="")
          numbers.push(trimmed.substr(6,4));
          input.value = numbers.join('-');
      
        }
      
      }
      

      演示stackblitz

      【讨论】:

        猜你喜欢
        • 2012-03-04
        • 2017-03-13
        • 1970-01-01
        • 2020-02-29
        • 2015-03-15
        • 1970-01-01
        • 1970-01-01
        • 2012-10-27
        相关资源
        最近更新 更多