ng2-validation combined US/Canada Phone 验证?

ng2-validation combined US/Canada Phone Validation?

我正在使用 ng2-validation which uses libphonenumber-js 来验证 phone 数字。我想在 phone 数字表单控件中允许美国和加拿大的 phone 数字。我目前正在传递 CustomValidators.phone('US') 作为表单控件验证器,它允许美国 phone 数字但不允许加拿大 phone 数字。

有没有办法使用此验证方法在表单控件中同时允许美国和加拿大 phone 数字?

从您正在使用的验证器函数查看 the source code

export const phone = (country: string): ValidatorFn => {
  return (control: AbstractControl): { [key: string]: boolean } => {
    if (isPresent(Validators.required(control))) return null;

    let v: string = control.value;

    return isValidNumber({phone: v, country}) ? null : {phone: true};
  };
};

您应该能够自己将这些与 or 结合起来(类似于此):

export const phone = (countries: string[]): ValidatorFn => {
  return (control: AbstractControl): { [key: string]: boolean } => {
    if (isPresent(Validators.required(control))) return null;

    let v: string = control.value;

    const validPhone: boolean = countries.map(c => isValidNumber({phone: v, c}).some(z => z);

    return validPhone ? null : {phone: true};
  };
};

然后在验证器内部,您可以传递国家代码列表:

phone('US', 'CAN')

我创建了一个包含以下内容的新文件 customPhoneValidator.ts

import { AbstractControl, ValidatorFn } from '@angular/forms';
import { isValidNumber, NationalNumber, CountryCode } from 'libphonenumber-js';

export const customPhoneValidator = (countries: CountryCode[]): ValidatorFn => {
    return (control: AbstractControl): { [key: string]: boolean } => {
        let v: NationalNumber = control.value;

        if (!v || v === '') return null;

        const validPhone: boolean = countries.map(c => isValidNumber(v, c)).some(z => z);

        return validPhone ? null : { phone: true };
    };
};

在使用验证器的组件中,我声明了 const customPhoneCountries: CountryCode[] = ['US', 'CA']; 并传递了 customPhoneValidator(customPhoneCountries) 作为表单控件的验证器。