We are using libphonenumber library for validating a phone number which user is expected to enter as a string.
Sample code that we use
var phoneNumberObj = phoneUtil.Parse(phoneNumber, default);
bool isValid = phoneUtil.IsValidNumber(phoneNumberObj);
here phoneNumber is a string containing the phone number with country code.
The expectation from user is that he/she will add country code prefix with '+' but in some cases users forget the '+' symbol. Is it safe to append '+' symbol (if not present) before validation? What if user forgets to add the country code, can it form a valid phoneNumber of other country if we append a '+' symbol?
What if user forgets to add the country code, can it form a valid phoneNumber of other country if we append a '+' symbol?
Yes.
A quick play around with the live libphonenumber demo found this example:
(321) 234-5678
, which would correctly be prefixed as +1 321-234-5678
3212345678
, and add +
instead of +1
+32 12 34 56 78
, which is the valid Belgian number 012 34 56 78
So the only way this can be safe is if you know which prefix you are expecting, and can validate the result on that basis.
For instance, if you know you are expecting UK numbers, you might have rules like this:
+
, assume it is in standard international format0
, assume it is a local format UK number (this is handled by libphonenumber if you give it a default country)44
, assume it was intended to be a leading +44