问题
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