PeakGen PeakGen -4 years ago 70
Java Question

How can I prevent bad inputs when storing phone numbers as strings?

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:


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

or maybe

Now there are
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download