ng2-validation结合了美国/加拿大电话验证? [英] ng2-validation combined US/Canada Phone Validation?
问题描述
我正在使用CustomValidators.phone('US')
作为表单控件验证器,该验证器允许使用美国电话号码,但不允许加拿大电话号码.
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?
推荐答案
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或(与之类似的东西)组合在一起:
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')
这篇关于ng2-validation结合了美国/加拿大电话验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!