Input formatting for JavaScript, TypeScript and browser-based forms: numerals, dates, times, card numbers, custom masks and opt-in phones, returned as a display value and a backend-ready value from one pure call, plus Intl helpers to display stored numbers, currency and dates, and dependency-free date tools to parse, format, change, compare and measure dates in any time zone. No DOM access, no framework runtime and no runtime dependency in the core.
Demo · Examples · Documentation · Changelog
- Installation
- Quick start
- HTML / CDN
- Capabilities
- API at a glance
- Documentation
- Changelog
- AI agent skill
- License
npm install @samline/formatterpnpm add @samline/formatterbun add @samline/formatterPackage tooling requires Node.js 20+; output targets ES2020. There is no stylesheet to import.
Format the visible field on every keystroke and mirror the raw value into the field your backend reads.
<label for="phone">Mobile phone</label>
<input id="phone" type="text" inputmode="tel" autocomplete="tel" />
<input type="hidden" name="phone" />import { format } from '@samline/formatter'
import { registerPhone } from '@samline/formatter/phone'
registerPhone() // phones are opt-in since 3.0.0
const field = document.querySelector('#phone')
const hidden = document.querySelector('input[name="phone"]')
field.addEventListener('input', () => {
const { formatted, raw } = format(field.value, 'phone', { country: 'MX' })
field.value = formatted // '55 1234 5678'
hidden.value = raw // '5512345678'
})The same call works for every type:
format('1234567.891', 'numeral', { prefix: '$', numeralDecimalScale: 2 })
// { formatted: '$1,234,567.89', raw: '1234567.89', type: 'numeral' }
format('1990-12-31', 'date', { dateRawPattern: ['Y', 'm', 'd'] })
// { formatted: '31/12/1990', raw: '1990-12-31', type: 'date' }
format('4111111111111111', 'creditCard')
// { formatted: '4111 1111 1111 1111', raw: '4111111111111111', type: 'creditCard' }
format('12345678', 'general', { prefix: 'ORD-', blocks: [4, 4], delimiter: '-' })
// { formatted: 'ORD-1234-5678', raw: '12345678', type: 'general' }format() is pure and synchronous: there is no instance to create or destroy. Your code owns the listener, labels, error messages and caret behavior.
Pad a money field when it loses focus, and show stored values in a locale:
format('1234.5', 'numeral', { prefix: '$', numeralDecimalPadding: true })
// { formatted: '$1,234.50', raw: '1234.5', type: 'numeral' }
format('1234.5', 'numeral', { prefix: '$', numeralDecimalPadding: true, rawDecimalPadding: true })
// { formatted: '$1,234.50', raw: '1234.50', type: 'numeral' }
import { formatCurrency, formatDate, formatRelativeTime } from '@samline/formatter/intl'
formatCurrency(1234.5, { locale: 'es-MX', currency: 'MXN' }) // '$1,234.50'
formatDate('2026-11-12', { locale: 'es-MX', preset: 'long' }) // '12 de noviembre de 2026'
formatRelativeTime(threeDaysAgo, { locale: 'es-MX' }) // 'hace 3 días'
import { addDate, diffDate, formatDatePattern, parseDate } from '@samline/formatter/date'
const checkIn = parseDate('24/12/2026', { format: 'DD/MM/YYYY' })
const checkOut = addDate(checkIn, 3, 'day')
diffDate(checkOut, checkIn, 'day') // 3
formatDatePattern(checkOut, 'dddd D [de] MMMM', { locale: 'es-MX' }) // 'domingo 27 de diciembre'
parseDate('2026-02-30', { format: 'YYYY-MM-DD' }) // undefined: no error object, check before useLoad the versioned standalone script, then use window.Formatter:
<script src="https://cdn.jsdelivr.net/npm/@samline/formatter@3.3.1/dist/browser/formatter.phone.global.js"></script>
<script>
const { format, regex } = window.Formatter
console.log(format('5512345678', 'phone').formatted) // '55 1234 5678'
</script>Both scripts are minified IIFEs that define window.Formatter with format, intl, regex, checks and version:
| Script | Phones | Size (minified) |
|---|---|---|
https://cdn.jsdelivr.net/npm/@samline/formatter@3.3.1/dist/browser/formatter.global.js |
no | about 36 KB (14 KB gzip) |
https://cdn.jsdelivr.net/npm/@samline/formatter@3.3.1/dist/browser/formatter.phone.global.js |
registered | about 174 KB (46 KB gzip) |
For the date tools, add formatter.date.global.js from the same folder after either script (about 24 KB minified, 9 KB gzip); it adds window.Formatter.date.
Pin the version in production, or self-host the same file. 3.0.0 renamed the former global.global.js.
- Opt-in phones for any country through libphonenumber-js, with international
+numbers kept inraw. - Numerals with currency prefixes or suffixes, regional decimal marks, decimal and integer limits, optional decimal padding and positive-only values.
Intldisplay helpers for numbers, currency, percentages, dates and relative time, with safe handling of empty and invalid values.- Date tools on native
DateandIntl: parsing and printing with tokens (DD/MM/YYYY,dddd D [de] MMMM) in every locale, calendar math that keeps month ends and daylight saving right, comparisons, locale and ISO weeks, any IANA time zone and durations. Each function is a separate export. - Dates and times in any segment order, with a separate raw pattern (for example ISO for storage) and automatic recognition of stored values.
- Card numbers grouped by brand, and brand detection.
- Free text with title, sentence or capitalize casing (
'text') and live URL slugs ('slug'), built on @samline/string. - General block masks with delimiters, case transforms, numeric-only input and locked or typed prefixes and suffixes.
- A validation catalog that pairs each pattern with its error message: Mexican IDs (RFC, CURP, INE, CLABE, NSS), US IDs (SSN, ITIN, EIN, routing numbers), IBAN, BIC, EU VAT, postal codes for 24 countries, email, URLs, IPs and more, plus rules built from the same options as
format()for dates, times and numbers. - Check-digit validators (
isValidCard,isValidCurp,isValidRfc,isValidClabe,isValidIban…) that catch the typos a pattern cannot.
Working examples cover twenty real fields: phones by country, currencies checked with regex.numeral(options), quantities, ISO dates, card expiry, times, a date read back in any language, a strict date check and a date moved by months with the date tools, card numbers, order references, units, promo codes, ZIP codes, postal codes by country, CURP and IBAN with check digits, hex colors and validation rules. Framework integrations covers React, Vue, Svelte, vanilla and server-side use.
formatted is for people; submit raw. Prefixes and suffixes stay out of raw unless rawPrefix / rawSuffix is set, numerals always use a dot for decimals, and dates follow their raw pattern. Formatting a displayed value again returns the same raw. See configuration.
| API | Purpose |
|---|---|
format(value, formatType, options?) |
Format |
'phone', 'numeral', 'date', 'time', 'creditCard', 'creditCardType', 'general', 'text', 'slug' |
Format types |
FORMAT_TYPES, isFormatType() |
Type checks |
regex (static entries and the digits, phone, creditCard, url, uuid, date, time, numeral, postalCode, password and custom builders) |
Validation |
isLuhn(), isValidCard(), isValidClabe(), isValidNss(), isValidCurp(), isValidRfc(), isValidIban(), isValidRoutingNumber(), isValidDniEs() |
Check digits |
getRawValue(), stripPrefixAndSuffix(), getDateValueFromRaw(), getTimeValueFromRaw(), looksLikeRawDateValue(), looksLikeRawTimeValue(), isPhoneRegistered() |
Helpers |
registerPhone(), formatPhone() from @samline/formatter/phone |
Phones |
formatNumber(), formatCurrency(), formatPercent(), formatDate(), formatRelativeTime() from @samline/formatter/intl |
Display |
parseDate(), formatDatePattern(), addDate(), diffDate(), startOfDate(), isSameDate(), createDate(), formatDuration() and more from @samline/formatter/date |
Dates |
window.Formatter.format, window.Formatter.intl, window.Formatter.regex, window.Formatter.checks, window.Formatter.version, window.Formatter.date (add-on) |
Browser global |
| Entrypoint | When to use |
|---|---|
@samline/formatter |
ESM and CommonJS with type declarations; format alone about 16 KB minified (6 KB gzip), every export about 32 KB (12 KB gzip). |
@samline/formatter/vanilla |
The same API under an explicit subpath. |
@samline/formatter/phone |
registerPhone() and formatPhone(); adds libphonenumber-js. |
@samline/formatter/intl |
Intl display helpers; no dependencies. |
@samline/formatter/date |
Date tools; no dependencies; every function under 10 KB gzip together. |
@samline/formatter/browser |
The standalone IIFE without phones (formatter.global.js). |
@samline/formatter/browser/phone |
The standalone IIFE with phones (formatter.phone.global.js). |
@samline/formatter/browser/date |
The date add-on for either IIFE (formatter.date.global.js). |
import { format, regex } from '@samline/formatter'
const rule = regex.phone({ length: 10 })
const { raw } = format(field.value, 'phone')
field.setCustomValidity(rule.pattern.test(raw) ? '' : rule.errorMessage)Patterns give quick feedback; validate again on the server. Card formatting is not payment validation.
The package includes declarations. Import FormatType, FormatOptions and FormatterResult for formatting, DatePatternType, TimePatternType and NumeralThousandsGroupStyle for patterns, RegexEntry, RegexKey and Regex for validation, the Intl*Options types from @samline/formatter/intl, and DateOptions, ParseDateOptions, DurationInput and the other date types from @samline/formatter/date. See the TypeScript reference.
Read the documentation for the full guides and API contracts, and explore working examples with complete and separate source files for both loading modes.
| Guide | What it covers |
|---|---|
| Getting started | Installation, the first field and starter files. |
| Configuration | Every option per type, with prefix and suffix rules. |
| Validation patterns | The regex catalog and its parametric builders. |
| Framework integrations | React, Vue, Svelte, vanilla and server-side use. |
| Styling and UX | Markup, input attributes, validation states and caret. |
| Recipes | End-to-end patterns for real forms. |
| API reference | format() and the helpers, with errors and returns. |
| Intl display helpers | Numbers, currency, dates and relative time on Intl. |
| Date tools | Parsing, tokens, calendar math, time zones, durations. |
| Entrypoints | Every subpath, the browser builds and their sizes. |
Read CHANGELOG.md or the published changelog for release history and explicitly marked breaking and behavior changes. Review the notes before upgrading.
- Phones are opt-in. Call
registerPhone()from@samline/formatter/phoneonce, and importformatPhonefrom that subpath; until thenformat(value, 'phone')throws aTypeErrorthat says so. - The browser script
global.global.jsis nowformatter.phone.global.js(with phones) orformatter.global.js(without). cleave-zenis no longer a dependency; its engine is maintained in the package.numeralThousandsGroupStyletakes plain strings ('thousand','lakh','wan','none').- Engine fixes change a few outputs: a
','decimal mark groups with'.'by default, Mastercard detection is limited to 2221–2720, a 12-hour clock turns hour00into12, and numeralrawkeeps only a leading minus.
Read the 3.0.0 notes before upgrading.
The Formatter skill describes 3.0 integration: loading modes, the formatted/raw contract, options per type, validation and host ownership. Pass it to an agent or install it using a skills-compatible tool. Verify the installed package version before applying its guidance.
The maintained repository source and website download are the same file.
Download SKILL.md into a formatter/ folder in your agent's supported skill directory. For agents that discover project skills from .agents/skills/:
mkdir -p .agents/skills/formatter
curl --fail --location https://samline.github.io/formatter/skills/formatter/SKILL.md \
--output .agents/skills/formatter/SKILL.mdWhen working from this repository, copy skills/formatter/SKILL.md instead. Keep the filename SKILL.md; discovery paths and invocation syntax depend on the agent.
MIT — LICENSE.md. The formatting engine includes code adapted from cleave-zen (MIT); its notice is in THIRD_PARTY_NOTICES.md.