Created
February 8, 2018 19:54
-
-
Save djabif/2145b543ec916ec23d89effc4c1637d4 to your computer and use it in GitHub Desktop.
phone 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
import { AbstractControl, ValidatorFn } from '@angular/forms'; | |
import 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: boolean = 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(); | |
let phoneNumber = "" + phoneControl.value + "", | |
region = countryControl.value.iso, | |
number = phoneUtil.parse(phoneNumber, region), | |
isValidNumber = phoneUtil.isValidNumber(number); | |
if(isValidNumber){ | |
return null; | |
} | |
}catch(e){ | |
return { | |
validCountryPhone: true | |
}; | |
} | |
return { | |
validCountryPhone: true | |
}; | |
} | |
else{ | |
return null; | |
} | |
}; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment