Overview
TheAsYouTypeFormatter class provides real-time formatting of phone numbers as they are entered, digit by digit. This is particularly useful for creating user-friendly input fields that automatically format phone numbers while users type.
The
AsYouTypeFormatter should be obtained from PhoneNumberUtil::getAsYouTypeFormatter() rather than instantiating it directly.Getting an Instance
To use the AsYouTypeFormatter, obtain an instance throughPhoneNumberUtil:
The country/region code where the phone number is being entered (e.g., ‘US’, ‘GB’, ‘DE’)
Methods
inputDigit()
Formats a phone number on-the-fly as each digit is entered.The most recently entered digit of a phone number. Formatting characters are allowed, but as soon as they are encountered, this method formats the number as entered and not “as you type” anymore. Full width digits and Arabic-Indic digits are allowed and will be shown as they are.
string - The partially formatted phone number
Example: Progressive Formatting
clear()
Clears the internal state of the formatter so it can be reused for formatting another number.Always call
clear() before formatting a new phone number to ensure the formatter starts with a clean state.Example: Reusing the Formatter
inputDigitAndRememberPosition()
Same asinputDigit(), but remembers the position where the character is inserted. This is useful for maintaining cursor position in text inputs.
The most recently entered digit of a phone number
string - The partially formatted phone number
The remembered position can be retrieved later using getRememberedPosition() and will be automatically adjusted if additional formatting characters are inserted or removed.
getRememberedPosition()
Returns the current position in the partially formatted phone number of the character that was previously passed toinputDigitAndRememberPosition().
int - The position in the formatted string
Complete Usage Example
Use Cases
Form Input Validation
Ideal for enhancing user experience in phone number input fields:Real-time JavaScript Integration
Use with AJAX to format numbers as users type:Important Notes
- The formatter intelligently detects international dialing prefixes (IDD) and country codes
- National prefixes are automatically handled based on the region
- Formatting patterns are selected based on the leading digits entered
- Full-width digits and Arabic-Indic digits are supported and normalized
- The formatter maintains state across multiple
inputDigit()calls - Use
clear()to reset the formatter for a new number
Related
- PhoneNumberFormat - Format constants for final number formatting
- PhoneNumberUtil - Main utility class for phone number operations