When we need to store phone numbers in database, we may have different concerns to think about. I just want to talk about it casually.
Do we need to display the country flag beside the phone number?
Perhaps you store the country code in the database and use it to determine which country it belongs. However, there are some countries having the same country code.
For example, do you know which country this phone number +1 (800) 642 7676
belongs to? It is the phone number of Microsoft US support.
There are many countries with country code 1
.
Therefore, you should also store the country to the database too. Personally I prefer ISO 3166 format (e.g. JP for Japan).
Should it be unique in the database?
Usually, you may avoid having multiple users using the same phone number, so you add UNIQUE
constraint to the database column. Before you store it to database, you should normalize it first to ensure each input is using the same format. Otherwise, 6427676
, 642-7676
and 642 7676
will be treated as different numbers.
E.164 format ensures each device having a globally unique number.
How to make life easier?
libphonenumber is a library created by Google. There are implementations for different languages. It can validate, format, parse phone number.
It also includes a page about the fun facts of phone number. Enjoy!
Top comments (0)