ng2-validation结合了美国/加拿大电话验证? [英] ng2-validation combined US/Canada Phone Validation?

查看:97
本文介绍了ng2-validation结合了美国/加拿大电话验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ng2-validation github.com/catamphetamine/libphonenumber-js"rel =" nofollow noreferrer> libphonenumber-js 来验证电话号码.我想在电话号码表单控件中同时允许美国和加拿大的电话号码.我当前正在通过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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆