Skip to content

Instantly share code, notes, and snippets.

@ramziddin
Last active January 12, 2025 19:17
Show Gist options
  • Save ramziddin/8a7699ec635c74ea0cd903461d6cb23c to your computer and use it in GitHub Desktop.
Save ramziddin/8a7699ec635c74ea0cd903461d6cb23c to your computer and use it in GitHub Desktop.

Revisions

  1. ramziddin revised this gist Nov 20, 2024. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions phone-input.ts
    Original file line number Diff line number Diff line change
    @@ -17,6 +17,7 @@ function PhoneInput(props: ComponentProps<"input">) {
    onChange={(event) => {
    setValue(event.target.value)
    }}
    inputMode="tel"
    {...props}
    />
    )
  2. ramziddin created this gist Nov 20, 2024.
    23 changes: 23 additions & 0 deletions phone-input.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    import { ComponentProps, useState } from "react"

    function PhoneInput(props: ComponentProps<"input">) {
    const [value, setValue] = useState<string>("+998")

    const formattedValue = value
    .replaceAll(" ", "") // remove whitespace
    .slice(4) // strip the country code
    .match(/(\d{1,2})?(\d{1,3})?(\d{1,2})?(\d{1,2})?/)! // split into multiple components
    .toSpliced(0, 1, "+998") // replace global match with country code
    .filter(Boolean) // remove empty components
    .join(" ") // convert array back to string joined by spaces

    return (
    <input
    value={formattedValue}
    onChange={(event) => {
    setValue(event.target.value)
    }}
    {...props}
    />
    )
    }