Search code examples
libphonenumber

Can I safely append '+' to a phone number before validation


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?


Solution

  • 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:

    • Take the valid US number (321) 234-5678, which would correctly be prefixed as +1 321-234-5678
    • Enter it as 3212345678, and add + instead of +1
    • The result is interpreted as +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:

    • If it has a leading +, assume it is in standard international format
    • If it has a leading 0, assume it is a local format UK number (this is handled by libphonenumber if you give it a default country)
    • If it has a leading 44, assume it was intended to be a leading +44
    • If it has any other leading digit, reject it