ng2-validation combined US/Canada Phone Validation?

二次信任 提交于 2019-12-11 10:25:14

问题


I am using ng2-validation which uses libphonenumber-js to validate phone numbers. I would like to allow both US and Canadian phone numbers in a phone number form control. I am currently passing CustomValidators.phone('US') as the form control validator, which allows US phone numbers but disallows Canadian phone numbers.

Is there a way to allow both US and Canadian phone numbers in the form control with this validation method?


回答1:


Looking at the source code from the validator function you're using:

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

You should be able to combine these on your own with an or (something along the lines of this):

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

Then inside of your validator, you can pass a list of country codes:

phone('US', 'CAN')



回答2:


I made a new file customPhoneValidator.ts containing the following:

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

In the component which uses the validator, I declared const customPhoneCountries: CountryCode[] = ['US', 'CA']; and passed customPhoneValidator(customPhoneCountries) as a validator for the form control.



来源:https://stackoverflow.com/questions/54676826/ng2-validation-combined-us-canada-phone-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!