Search code examples
angularlibphonenumber

ng2-validation combined US/Canada Phone Validation?


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?


Solution

  • 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')