角材料设计中的电话号码模式验证

时间:2019-02-14 08:36:40

标签: angular angular-material

我想使用棱角分明的设计代码来验证电话号码,但是即使我输入了有效的电话号码,下面的代码也无法使用

 <mat-form-field class="example-full-width">
                <input matInput placeholder="Phone number" formControlName="PhoneNumber"
                   [errorStateMatcher]="matcher" [(ngModel)]="PhoneNumber" required pattern="[6-9]\\d{9}" maxlength="10">
                     <mat-hint>Errors appear instantly!</mat-hint>
                     <mat-error *ngIf="emailForm.get('PhoneNumber').hasError('required')">
                       Phone number is <strong>required</strong>
                     </mat-error>
                      <mat-error *ngIf="!emailForm.get('PhoneNumber').hasError('required') &&emailForm.get('PhoneNumber').hasError('pattern')">
                      Please enter valid mumber
                     </mat-error>
          </mat-form-field>

    ngOnInit() {

    //Form Group
    this.emailForm = new FormGroup({
      PhoneNumber:new FormControl('',[Validators.pattern(/^[6-9]\d{9}$/)]),
    });
}

https://stackblitz.com/edit/angular-2m1vdq-7vzaq8?file=app%2Finput-error-state-matcher-example.html

3 个答案:

答案 0 :(得分:0)

您可以尝试以下对我有用的正则表达式

/ ^ [0-9] {10,10} $ /

答案 1 :(得分:0)

昨天我遇到了同样的问题,我的问题是从formControl删除模式,然后插入html

      <input matInput placeholder="Phone number" formControlName="PhoneNumber"
     [errorStateMatcher]="matcher" [(ngModel)]="PhoneNumber"
 required pattern="^[6-9]\d{9}$" maxlength="10">


            ngOnInit() {

            //Form Group
            this.emailForm = new FormGroup({
              PhoneNumber:new FormControl('',[]),
            });
        }

这是我如何使用它的示例:

      <mat-form-field class="rung">
        <input matInput [formControl]="selectRung" [(ngModel)]="rung"
        placeholder="Rung" type="number" pattern="^\d*[0-9]\d*$"
        name="rung" [value]="rung" min="0" id="rung"
          required="true">
          <mat-error *ngIf="selectRung.hasError('required')">Rung is required!</mat-error>
          <mat-error *ngIf="selectRung.hasError('pattern')">Only positive or 0!</mat-error>
      </mat-form-field>

和.ts

  selectRung = new FormControl(null, [Validators.required]);

对我来说很好

您还可以在此网站上检查自己的模式,如果其正常运行https://regex101.com/

答案 2 :(得分:0)

尝试一下,

  ngOnInit() {

    let MOBILE_PATTERN = /[0-9\+\-\ ]/;

    this.emailForm = new FormGroup({
      PhoneNumber:new FormControl('',[Validators.pattern(MOBILE_PATTERN)])
    });
  }