Created
November 18, 2024 20:49
-
-
Save bertybot/02470d3b2e0fbfb5c0e2a4fab7689b0f to your computer and use it in GitHub Desktop.
Svelte Phone Formatter Action With Built In Validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { ActionReturn } from "svelte/action"; | |
import { AsYouType, isValidPhoneNumber } from 'libphonenumber-js/min'; | |
interface Parameter { | |
countryCode: 'US' | |
} | |
export function phone_formatter(node: HTMLInputElement, params: Parameter = { countryCode: 'US' }): ActionReturn<Parameter> { | |
let value: string[] = [] | |
const handleInput = () => { | |
value = [...node.value] | |
node.setCustomValidity('') | |
if (!isValidPhoneNumber(value.join(''), params.countryCode)) { | |
node.setCustomValidity('Please Enter a valid phone number') | |
} | |
} | |
const keyDown = (e: KeyboardEvent) => { | |
const isText = /^[0-9a-zA-Z]$/i.test(e.key) | |
if (!isText) { | |
//Handle everything that is not text default way | |
return; | |
} | |
e.preventDefault(); | |
e.stopImmediatePropagation(); | |
const isNumber = /^[0-9]$/i.test(e.key) | |
if (!isNumber) { | |
return; //Ignore Letters | |
} | |
const formatter = new AsYouType(params.countryCode); | |
const selectionStart = node.selectionStart || 0; | |
const selectionEnd = node.selectionEnd || 0; | |
if (selectionStart !== selectionEnd) { | |
value.splice(selectionStart, selectionEnd, e.key) | |
} else { | |
value.push(e.key) | |
} | |
const output = formatter.input(value.join('')); | |
node.value = output; | |
node.dispatchEvent(new Event('input')); | |
} | |
node.addEventListener('keydown', keyDown); | |
node.addEventListener('input', handleInput) | |
return { | |
destroy() { | |
node.removeEventListener('keydown', keyDown); | |
node.removeEventListener('input', handleInput); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment