What is a good data structure for storing phone numbers in database fields? I\'m looking for something that is flexible enough to handle international numbers, and also som
Ok, so based on the info on this page, here is a start on an international phone number validator:
function validatePhone(phoneNumber) {
var valid = true;
var stripped = phoneNumber.replace(/[\(\)\.\-\ \+\x]/g, '');
if(phoneNumber == ""){
valid = false;
}else if (isNaN(parseInt(stripped))) {
valid = false;
}else if (stripped.length > 40) {
valid = false;
}
return valid;
}
Loosely based on a script from this page: http://www.webcheatsheet.com/javascript/form_validation.php
The Wikipedia page on E.164 should tell you everything you need to know.
I think free text (maybe varchar(25)) is the most widely used standard. This will allow for any format, either domestic or international.
I guess the main driving factor may be how exactly you're querying these numbers and what you're doing with them.
I've used 3 different ways to store phone numbers depending on the usage requirements.
What about storing a freetext column that shows a user-friendly version of the telephone number, then a normalised version that removes spaces, brackets and expands '+'. For example:
User friendly: +44 (0)181 4642542
Normalized: 00441814642542
Storage
Store phones in RFC 3966 (like +1-202-555-0252
, +1-202-555-7166;ext=22
). The main difference from E.164 are
To optimise performance of view operations, store the phone in the National/International format next to the RFC 3966 field.
Don't store the country code in a separate field unless you have a serious reason for that. Why? Because you shouldn't ask for the country code on the UI.
Mostly, people enter the phones as they hear them. E.g. if the local format will start from 0
or 8
, it'd be annoying for the user to make the number transformation in the head (like, "OK, don't type '0', choose the country and type the rest of what the person said in this field").
Parsing
Google has your back and you can validate and parse any phone number with using their libphonenumber library. There are ports to almost any language.
So let the user just enter "0449053501
" or "04 4905 3501
" or "(04) 4905 3501
". The tool will figure out the rest for you.
See the official demo, to get a feeling of how much does it help.