Phone input that auto-formats digits as (123) 456-7890

You are tasked with developing a phone number parser component, focusing on dynamically formatting and validating user inputs. This parser transcends mere data format assurance; it enhances user experience and data integrity in web applications that necessitate phone number inputs. A phone number formatter usually builds on regular expressions.
The parser is a form with a text input labelled Phone Number and a Submit button. As users type, the input field automatically formats the numbers into a readable format (e.g., (123) 456-7890), providing immediate feedback crucial for usability and allowing users to correct mistakes in real-time.
On every change, keep only the digits (at most 10) and show them in the input like this:
123.(XXX) XXX, e.g. (123) 456.(XXX) XXX-XXXX, e.g. (123) 456-7890.(123)4567, formats it again: (123) 456-7.In addition to formatting, the parser incorporates validation logic to confirm inputs adhere to a standard 10-digit phone number format, crucial for backend processing and frontend consistency, thus mitigating the risk of invalid data submissions. No error is shown before the first submit. When the form is submitted:
Required!.Invalid phone format. ex: (555) 555-5555.alert) is up to you.The component adeptly manages various user interactions. For example, when a user copies the phone number, only the digits (excluding formatting characters) are copied to the clipboard, ensuring phone numbers are usable in diverse contexts without necessitating additional formatting. Handle the input’s copy event: call event.preventDefault() and put the digits in event.clipboardData with setData('text/plain', digits).
Keep the formatted value in state (in React, with useState) or write it straight back into the input (in vanilla JS). Functions like cleanNumber strip out non-numeric characters for consistent storage, while formatPhoneNumber enhances displayed value readability.
The validateInput function encapsulates validation logic, checking for completeness and format correctness, thus maintaining form integrity and guiding user inputs.
The tests type into your input, click Submit, and read the screen like a real user would. You don’t need test ids, specific class names, or an exact HTML structure. They only check that:
aria-label, placeholder, or name containing “Phone”, and its value matches the formats above exactly.Submit button is a submit button inside a <form> (or any clickable element with that text).Required! or Invalid phone format after an invalid submit, and neither after a valid one. Capitalization and extra spacing don’t matter.copy event on the input puts only the digits in clipboardData and is default-prevented.