user268397
user268397

Reputation: 1927

How to Format a Phone Number

Here is an example of what I'm trying to do:

If a phone number is entered as 6123044356 it will display as (612)304-4356. Should a guest hit the backspace key 5 times instead of removing the last 4 numbers entered and the dash, remove the last 5 numbers entered. The phone number at that point would be displayed as (612)30. Should the guest hit the backspace key 3 more times the last 3 numbers displayed would be removed, not the parenthesis. The phone number would then be displayed as 61.

Any suggestions on how to do this?

Upvotes: 0

Views: 411

Answers (2)

anthonycr
anthonycr

Reputation: 4186

I would do it just like the dialer does it. That way is most intuitive.

Basically when they are typing, as soon as a number, say 1234567, gets to 7 digits, split it up like 123-4567 for the user. Then when it reaches 10 digits, 123-4567890, split it up like (123)456-7890 for them. When they reach 11 digits, change the format to 1-(234)567-8901.

When they are removing numbers from an 11 digit number, as soon as they hit 10 digits, change back to (123)456-7890. After that, as soon as the number of digits is less than 10, change the format back to 123-456789. Keep it in that format until they reach six digits when you just change it to 123456.

By changing the numbers to and from recognizable forms when a user reaches a certain number of digits, it subtly alerts the user that they have either created a real number, or there are too many or not enough digits for this to be a real number.

I suggest using the following thresholds:

  • 11 digits: 1-(234)567-8901
  • 10 digits: (123)456-7890 (anything less than this looks like 7 digits with digits on the end)
  • 7 digits: 123-4567 (anything less just removes the dash).

I hope that makes sense. I do not think the user should have to input/erase any extra characters like parentheses and dashes. It should all be taken care of by the app.

Upvotes: 0

Blaz
Blaz

Reputation: 2075

Look at libphonenumber library. It has AsYouTypeFormatter class in it, which will handle this for you.

Alternatively you can use PhoneNumberFormattingTextWatcher which basically does the same thing. You would use it like so:

editText.addTextChangeListener(new PhoneNumberFormattingTextWatcher());

Upvotes: 1

Related Questions