ReactCHALLENGES
Challenges Referral Program Report a Bug

© 2025 reactchallenges.com

Terms of ServicePrivacy PolicyContact

#38Phone Number Field
60min

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)
  • Restrict typing so the input only allows:
    • Digits (0–9)
    • Spaces
    • A single leading + (never in the middle)
  • 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.ts to:
    • 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 select prop — ensure the UI updates accordingly.
  • all logic must be implemented in PhoneInput.tsx, utils.ts is 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.
  • 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

  1. renders input and select by default
  2. renders input only when select=false
  3. validates a correct phone number
  4. shows invalid message for incorrect phone
  5. updates input when selecting a country
  6. select updates automatically when typing a matching prefix
  7. does not allow non-numeric characters except + at the start and spaces
  8. formats the number to international format when valid
  9. updates validation message dynamically
  10. detects country automatically when select is false
  11. does not duplicate prefix when same country is selected again
Subscribe to StartBack