如何在角材料反应形式上验证手机号码?

时间:2019-11-13 02:24:46

标签: regex angular angular-material angular-reactive-forms angular-forms

app.component.ts

phoneFormControl = new FormControl('', [
Validators.required,
Validators.pattern("[6-9]\d{9}")
])

app.component.html

<mat-form-field>
    <input matInput placeholder="Phone Number" [formControl]="phoneFormControl>
    <mat-error *ngIf="phoneFormControl.hasError('required')">
         Phone Number is <strong>required</strong>
    </mat-error>
</mat-form-field>

表单提交错误

pattern:
   actualValue: "9120227914"
   requiredPattern: "^[6-9]d{9}$"

2 个答案:

答案 0 :(得分:0)

  1. npm install --save-prod google-libphonenumber

  2. phone.validator.ts

import { AbstractControl, ValidatorFn } from '@angular/forms';
import * as libphonenumber from 'google-libphonenumber';

export class PhoneValidator {
  // Inspired on: https://github.com/yuyang041060120/ng2-validation/blob/master/src/equal-to/validator.ts
  static validCountryPhone = (countryControl: AbstractControl): ValidatorFn => {
    let subscribe = false;
    return (phoneControl: AbstractControl): {[key: string]: boolean} => {
      if (!subscribe) {
        subscribe = true;
        countryControl.valueChanges.subscribe(() => {
          phoneControl.updateValueAndValidity();
        });
      }

      if (phoneControl.value !== '') {
        try {

          const phoneUtil     = libphonenumber.PhoneNumberUtil.getInstance();
          const phoneNumber   = '' + phoneControl.value + '';
          const region        = countryControl.value;
          const pNumber       = phoneUtil.parseAndKeepRawInput(phoneNumber, region.iso);
          const isValidNumber = phoneUtil.isValidNumber(pNumber);

          if (isValidNumber) {
            return undefined;
          }
        } catch (e) {
          console.log(e);
          return {
            validCountryPhone: true
          };
        }

        return {
          validCountryPhone: true
        };
      } else {
        return undefined;
      }
    };
  }
}
  1. (您的)app.component.ts
phoneFormControl = new FormControl('', [
  Validators.compose([
    Validators.required,
    PhoneValidator.validCountryPhone(country)
  ])
);
  1. (您的)app.component.html
<mat-form-field>
    <input matInput placeholder="Phone Number" [formControl]="phoneFormControl>
    <mat-error *ngIf="phoneFormControl.hasError('required') || phoneFormControl.hasError('validCountryPhone')">
        Phone Number is <strong>required</strong>
    </mat-error>
</mat-form-field>

答案 1 :(得分:0)

由于您的模式是string,因此应该转义了反斜杠。

因此,您想要Validators.pattern("[6-9]\d{9}")而不是Validators.pattern("[6-9]\\d{9}")

示例

readonly phoneFormControl = new FormControl('', [
  Validators.required, Validators.pattern(("[6-9]\\d{9}"))
]);

Working demo