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:

    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: