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

前端 未结 3 1336
闹比i
闹比i 2021-01-06 07:14

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

3条回答
  •  执笔经年
    2021-01-06 07:48

    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.

提交回复
热议问题