4

I am creating a phonebook program that can read VCards. The problem is with phone numbers. Normally, they will be like this in the United States:

0771234560

But if the phone number is from a foreign country, it would look like this.

+94771234560 or maybe (22)772324000

Now there are + and () signs to deal with! I am currently converting phone numbers (VCards contain them as Strings) to numbers. However, if I take allow phone numbers as strings, then a user could do something crazy, like insert a name as a phone number in the contact form.

How can I store phone numbers as strings but prevent problematic entries?

TylerH
  • 20,799
  • 66
  • 75
  • 101
PeakGen
  • 21,894
  • 86
  • 261
  • 463
  • I would strip out all non-digit characters. Those are display issues. – duffymo Sep 08 '12 at 14:37
  • I would use a string and use http://stackoverflow.com/questions/8196771/format-a-string-using-regex-in-java to make it in the correct regex – 0x90 Sep 08 '12 at 14:38

3 Answers3

12

Definitely use a string, but validate it. Just because it's a string doesn't mean you have to accept any data. You should consider using a regular expression (or perhaps a series of regular expressions) to validate the data.

Don't just limit it to specific characters - for example, you don't want to accept ")0(" as a phone number - use sensible patterns. The Wikipedia page on local conventions for phone numbers may prove helpful on this front - or you could look for other sources. You may also want to consider being somewhat lenient, as not everyone will follow exact patterns. There's a delicate balance to be achieved though.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
5

Don't use a numeric type for phone numbers, stick with a String.

Do some form of input validation. Define some restrictions on your phone numbers, and when reading the card, check the String against your format: if the phone number doesn't match your restrictions, then reject it.

Search around this site for questions/answers regarding phone number validation.

pb2q
  • 58,613
  • 19
  • 146
  • 147
4

What would adding two phone numbers mean? So, IMO, not a number.

You should still attempt to validate, but if you want to accept any and all arbitrary international numbers, including local conventions for how they're written, that'll be frustrating.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302