Phone number validation example code with google-libphonenumber and libphonenumber-js library in Angular
I needed to validate entered phone numbers from all possible countries in Angular. Actually, I also preferred to get my country code list dynamically.
I have used Google’s i18n libphonenumber library for Java projects as I described in my previous post:
google-libphonenumber
Now, it is time to implement in Angular. You can read https://www.npmjs.com/package/google-libphonenumber for more details about the library.
I implemented the way described in the post below from Stackoverflow, you can also check the example code:
I installed required dependencies:
npm install --save google-libphonenumber
npm install --save-dev @types/google-libphonenumber
To get country code list (as numeric values) in my component:
On the front end side, country code selectbox and phone number input fields are separate, so I will implement a custom validator on multiple fields.
This is my separate custom validator file:
FormBuilder is used to create my form fields object. In my component .ts file:
This is the html side (see hasError(‘phoneNumberInvalid’ checks):
libphonenumber-js
There is also another library called “libphonenumber-js” swith more weekly downloads (https://www.npmjs.com/package/libphonenumber-js).
It has a clear description and examples to show how to use it. You can import methods directly for use.
import {
isPossiblePhoneNumber,
isValidPhoneNumber,
validatePhoneNumberLength
} from 'libphonenumber-js'isValidPhoneNumber('8 (800) 555-35-35', 'RU') === true
You can also reach metadata file with Metadata and get certain properties from it (which I mentioned about in my Java version library blog post):
import { Metadata } from 'libphonenumber-js'
const metadata = new Metadata()
metadata.selectNumberingPlan('US')
console.log(metadata.numberingPlan.leadingDigits())
There is also an option called “As You Type” formatter in both libraries. Besides beforehand validation, this may be a good option to suggest flags or countries as you type, instead of showing all country codes as a list in a selectbox.
Happy Coding!