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

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

0771234560

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

+94771234560 or, possibly, (22)772324000

Now there are + and () icons! I am currently converting phone numbers (VCards contain them as strings) to numbers. However, if I resolve the phone numbers as strings, then the user can do something crazy, for example, insert the name as the phone number in the contact form.

How to save phone numbers as strings, but prevent problematic entries?

+4
source share
3 answers

Definitely use a string, but check it out. Just because a string does not 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 limit it to just specific characters β€” for example, you don’t want to accept ") 0 (" as a phone number - use reasonable templates. The Wikipedia page on local phone number arrangements may be useful on this front - or you could look for other sources. You You might also consider being somewhat condescending, as not everyone will follow exact patterns. A fragile balance needs to be achieved.

+12
source

Do not use the numeric type for phone numbers, stick with String .

Do some form of input validation. Define some restrictions on phone numbers, and, reading the card, check String for your format: if the phone number does not meet your restrictions, then reject it.

Search this site for questions / answers regarding checking your phone number.

+5
source

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

You should still try to check, but if you want to accept any and any arbitrary international numbers, including local agreements on how they are written, this will be frustrating.

+4
source

Source: https://habr.com/ru/post/1433139/


All Articles