-
-
Save jjvillavicencio/bcd5cf40d82bdbaee0297594a9e3d528 to your computer and use it in GitHub Desktop.
Angular Phone + Country Validator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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