#38Phone Number Field
Overview
Build a smart Phone Input that auto-detects the country, validates the number, and formats the input as you type.
Requirements
- Implement a phone input that supports two modes:
- With country selector (
select=true) - Input-only mode (
select=false)
- With country selector (
- Restrict typing so the input only allows:
- Digits (
0–9) - Spaces
- A single leading
+(never in the middle)
- Digits (
- When a valid prefix is typed, automatically detect the matching country and update the selector.
- When a country is selected from the dropdown, update the input with the corresponding calling code (e.g.,
+1,+44). - Use only the exported functions and lists from
utils.tsto:- Parse and validate phone numbers
- Provide the formatted international output (e.g.,
+44 7555 555555)
- Display a validation message:
"Valid phone"(green) when the number is valid"Invalid phone"(red) when the number is invalid
- Format the number automatically once it's considered valid.
Notes
- The component must behave differently depending on the
selectprop — ensure the UI updates accordingly. - all logic must be implemented in
PhoneInput.tsx,utils.tsis read only - The input should always normalize the value so that:
- A
+is automatically added if the user types digits without it. - Additional
+signs or invalid characters are removed.
- A
- Auto-selecting the country should work even if multiple countries share the same prefix; use the first matching prefix from the provided list in
utils.ts. - The validation message should only appear once the user has typed something (do not show anything on empty input).
- When a number becomes valid, display the formatted version in the input itself.
- When switching countries via the dropdown, the existing number should be replaced by the new country’s prefix only — do not keep leftover digits.
Tests
- renders input and select by default
- renders input only when select=false
- validates a correct phone number
- shows invalid message for incorrect phone
- updates input when selecting a country
- select updates automatically when typing a matching prefix
- does not allow non-numeric characters except + at the start and spaces
- formats the number to international format when valid
- updates validation message dynamically
- detects country automatically when select is false
- does not duplicate prefix when same country is selected again