Skip to content

Instantly share code, notes, and snippets.

@djabif
Last active February 28, 2023 12:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save djabif/8c29d5911df82adbf783ffb2d1f68829 to your computer and use it in GitHub Desktop.
Save djabif/8c29d5911df82adbf783ffb2d1f68829 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 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