(Angular2 / 4/5/6)如何根据国家/地区验证国际电话号码的长度

时间:2019-01-21 04:33:01

标签: angular validation angular6 phone-number

是否有一个图书馆/服务类可用于分别验证国际移动电话号码?例如。新加坡的手机号码必须为8位数字,中国的手机号码必须为11位数字,等等。目前,我正在以反应形式使用ng4-intl-phone,以允许用户输入其手机号码。

验证应根据每个国家/地区显示,而不是对国际电话号码的常规检查,例如该号码为3到14位数字(这是我以前使用的数字)。

感谢您的帮助!

更新

我暂时使用https://www.npmjs.com/package/ngx-international-phone-number。如果有人需要参考这些答案,我仍将其留在下面!

2 个答案:

答案 0 :(得分:2)

我已经在我的angular 6项目中使用了libphonenumber-js,它的运行情况非常好。

答案 1 :(得分:1)

这是我的自定义解决方案。在我的解决方案上效果很好。

请在您的项目中安装intl-tel-input

npm i intl-tel-input --save

然后按如下所示创建一个IntlTelInputComponent组件。

intl-tel-input.component.ts

import {
  AfterViewInit, Component, ElementRef, EventEmitter, Input, Output, ViewChild, forwardRef, Renderer
} from '@angular/core';
import 'intl-tel-input';
import * as jQuery from 'jquery';
import { NG_VALUE_ACCESSOR, ControlValueAccessor, } from '@angular/forms';

export interface ITimeInputFieldChanged {
  value: string;
  extension: string;
  numberType: string,
  valid: boolean;
  validationError: any
}

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => IntlTelInputComponent),
  multi: true
};

const noop = () => {
};

@Component({
  selector: 'intl-tel-input',
  templateUrl: './intl-tel-input.component.html',
  styleUrls: ['./intl-tel-input.component.scss'],
  providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})

export class IntlTelInputComponent implements ControlValueAccessor {

  @Input() fullValue: string;
  @Output() fullValueChange = new EventEmitter<ITimeInputFieldChanged>();
  @Input() id: string;
  @Input() intlOptions = {
    initialCountry: 'no',
    formatOnDisplay: true,
    separateDialCode: true,
    onlyCountries: ['no', 'be']
  };
  @Input() value: string;
  @Output() valueChange = new EventEmitter<string>();
  @Output() valueBlur = new EventEmitter<string>();
  @Output() valueFocus = new EventEmitter();
  @ViewChild('intlInput') intlInput: ElementRef;

  private extension: string;

  private onTouchedCallback: () => void = noop;
  private onChangeCallback: (_: any) => void = noop;

  constructor(
    private _renderer: Renderer) { }

  onInputChange(value: string) {
    const intlInput = jQuery(this.intlInput.nativeElement)
    this.value = value;
    this.valueChange.emit(value);
    this.fullValue = intlInput.intlTelInput('getNumber');
    this.extension = intlInput.intlTelInput('getSelectedCountryData').dialCode;
    const validationErrorCode = intlInput.intlTelInput('getValidationError');
    let validationMessage = 'VALID';
    switch (validationErrorCode) {
      case 1:
        validationMessage = 'INVALID_COUNTRY_CODE'
        break;
      case 2:
        validationMessage = 'TOO_SHORT'
        break;
      case 3:
        validationMessage = 'TOO_LONG'
        break;
      case 4:
        validationMessage = 'NOT_A_NUMBER'
        break;
      case 5:
        break;
      default:
        validationMessage = 'VALID'
        break;
    }
    this.fullValueChange.emit({
      value: value,
      extension: this.extension,
      numberType: intlInput.intlTelInput('getNumberType'),
      valid: intlInput.intlTelInput('isValidNumber'),
      validationError: validationMessage
    });
    // this.writeValue(this.fullValue);
  }

  onBlur(value: string) {
    this.valueBlur.emit(value);
  }

  onFocus() {
    this.valueFocus.emit();
  }

  writeValue(value: any): void {

    if (value && (value !== this.value)) {
      this.fullValue = value;
      setTimeout(() => {
        const phoneInput = jQuery(`input#${this.id}`);
        phoneInput.intlTelInput('setNumber', this.fullValue);
      }, 100);
    }
  }
  registerOnChange(fn: any): void {
    this.onChangeCallback = fn;
  }

  registerOnTouched(fn: () => any): void { this.onTouchedCallback = fn; }

  setDisabledState?(isDisabled: boolean): void {
    throw new Error('Method not implemented.');
  }

}

intl-tel-input.component.html

<input #intlInput class="form-control"
[appIntlTelInput]="intlOptions"
[id]="id"
[ngModel]="value"
(ngModelChange)="onInputChange($event)"
(blur)="onBlur($event)"
(focus)="onFocus()"
>

intl-tel-input.component.scss

:host /deep/.intl-tel-input{
    display: block;
    .country-list{
        overflow-y: auto;
    }
}

intl-tel-input.directive.ts

import { Directive, ElementRef, Input, OnInit } from '@angular/core';
import 'intl-tel-input';
import * as jQuery from 'jquery';

@Directive({
  selector: '[appIntlTelInput]'
})
export class IntlTelInputDirective implements OnInit {

  @Input('appIntlTelInput') appIntlTelInput: any;
  constructor(private el: ElementRef) { }

  ngOnInit() {
    // jQuery.fn.intlTelInput.loadUtils('https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/11.0.12/js/utils.js');
    // jQuery.fn.intlTelInput.loadUtils('/intl-tel-input/build/js/utils.js');
    jQuery.fn.intlTelInput.loadUtils('assets/js/utils.js');
    jQuery(this.el.nativeElement).intlTelInput(this.appIntlTelInput);
  }
}

在表单内使用

 <intl-tel-input formControlName="Mobile" ></intl-tel-input>

希望这可以解决您的问题。它可以根据需要验证任何国际手机号码。