-1

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?

niteshb
  • 2,599
  • 2
  • 17
  • 16
  • Will append a '+' symbol only if it is not present, but still, I am not sure whether the number contains country code or not. Considering different country have different phone number lengths, not sure how can we validate. – niteshb Apr 03 '23 at 09:51
  • You can check if the input starts with +, if not, just add it. But maybe you can let the user choose the country first with a dropdown (format: [flag] +xx). Then only allow numbers in your input field, concat those together, and validate that. – Joost00719 Apr 03 '23 at 09:52
  • The input is actually coming from a text file, so there is no way to enforce policies. You can check if the input starts with +, if not, just add it. - This is exactly where I am not sure. If user forgets to add country code, then can adding '+' form a valid phone number of other country? If yes, then it is not serving my purpose. – niteshb Apr 03 '23 at 09:59

1 Answers1

1

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
IMSoP
  • 89,526
  • 13
  • 117
  • 169