Skip to content

Instantly share code, notes, and snippets.

@jjvillavicencio
Forked from djabif/phone.validator.ts
Created April 23, 2019 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjvillavicencio/bcd5cf40d82bdbaee0297594a9e3d528 to your computer and use it in GitHub Desktop.
Save jjvillavicencio/bcd5cf40d82bdbaee0297594a9e3d528 to your computer and use it in GitHub Desktop.
Angular Phone + Country Validator
//Complete example for Ionic Framework in: https://ionicthemes.com/tutorials/about/forms-and-validation-in-ionic
//Complete example for Angular 5 in: https://angular-templates.io/tutorials/about/angular-forms-and-validations
import { AbstractControl, ValidatorFn } from '@angular/forms';
import * as libphonenumber from 'google-libphonenumber';
export class PhoneValidator {
// Inspired on: https://github.com/yuyang041060120/ng2-validation/blob/master/src/equal-to/validator.ts
static validCountryPhone = (countryControl: AbstractControl): ValidatorFn => {
let subscribe = false;
return (phoneControl: AbstractControl): {[key: string]: boolean} => {
if (!subscribe) {
subscribe = true;
countryControl.valueChanges.subscribe(() => {
phoneControl.updateValueAndValidity();
});
}
if (phoneControl.value !== '') {
try {
const phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();
const phoneNumber = '' + phoneControl.value + '';
const region = countryControl.value;
const pNumber = phoneUtil.parseAndKeepRawInput(phoneNumber, region.iso);
const isValidNumber = phoneUtil.isValidNumber(pNumber);
if (isValidNumber) {
return undefined;
}
} catch (e) {
console.log(e);
return {
validCountryPhone: true
};
}
return {
validCountryPhone: true
};
} else {
return undefined;
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment