Small library. Clean input.

Formatter
Keep every field readable.

Input formatting for the fields that matter.
Group a phone, price a total, or store a date as ISO.

npm install @samline/formatter

One pure functionJavaScript & TypeScriptMIT licensed

Formatter studio
PhoneLive · formatted and raw

A phone number for any country

format(value, 'phone', { country })

Type or paste a number. The selected country decides the grouping; the backend receives digits, plus a leading + for international numbers.

Shown to people
55 1234 5678
Sent to your backend
5512345678

Changing the country reformats the same digits. One input listener and one change listener read the current country, so listeners never pile up.

AmountLive · formatted and raw

An amount with currency and decimals

format(value, 'numeral', { prefix, numeralDecimalScale })

Thousands separators and a currency prefix appear while typing. The raw value is a plain decimal string ready to parse on the server.

Shown to people
$1,234,567.89
Sent to your backend
1234567.89
regex.numeral(options)
Matches the mask

numeralDecimalScale limits the decimals. The prefix is display-only: raw never includes it. regex.numeral(options) takes the same options, so the rule accepts exactly what the mask writes.

DateLive · formatted and raw

A date shown locally, stored as ISO

format(value, 'date', { datePattern, delimiter, dateRawPattern, dateRawPatternDelimiter })

People read day/month/year; the API stores year-month-day. A server value such as 1990-12-31 is recognized and converted for display.

Shown to people
31/12/1990
Sent to your backend
1990-12-31
regex.date
Please enter a valid date (DD/MM/YYYY).

interpretInputAs: "auto" treats a complete value without the display delimiter as raw. Partial or delimited values are treated as typing.

CardLive · formatted and raw

A card number with its brand

format(value, 'creditCard')

Grouping follows the detected card brand. The same digits drive a brand badge and a paired validation message.

Shown to people
4111 1111 1111 1111
Sent to your backend
4111111111111111
Brand
visa
regex.creditCard
Card number length is valid

creditCardType returns the brand as formatted and the digits as raw. Formatting is not payment validation: rely on your payment provider for that.

MaskLive · formatted and raw

An order reference with a fixed prefix

format(value, 'general', { prefix, blocks, delimiter, numericOnly })

The ORD- prefix is locked, digits are grouped by blocks, and the backend receives only the digits. Deleting part of the prefix restores it.

Shown to people
ORD-2026-1105
Sent to your backend
20261105
regex.digits(8)
Complete reference

Pasted values that already include the prefix are accepted. Add rawPrefix: true when the backend stores ORD- as part of the value.

RulesLive · pattern and message

Validation rules with ready messages

regex[rule].pattern.test(value)

Choose a rule from the regex catalog and type a value. Each rule pairs its pattern with the message to show, so the two never drift apart.

Pattern
^(?=.{1,254}$)(?=[^@]{1,64}@)[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?\.)+(?:\p{L}{2,63}|xn--[a-zA-Z0-9-]{1,59})$
Result
Looks valid

Static rules are records; parametric ones such as password() are called first. Validate again on the server: these patterns give quick feedback.

ONE SMALL SCRIPT. RIGHT AT HOME IN YOUR STACK.

JavaScript TypeScript React Vue Svelte Shopify WordPress
01 / More than a mask

Formatted while typing.
Clean when it is sent.

Two outputs, one call

format() returns formatted for the visible field and raw for the hidden input or request body, so the two never drift apart.

Your field, your markup

Formatter never touches the DOM. Labels, error messages, autocomplete, inputmode and caret behavior stay under your control.

Pure and stateless

There is no instance to create or destroy. Call it on every input event, on the server, or in a test with the same result.

Seven format types

Numerals, dates, times, card numbers and brands, and general block masks from a built-in engine, plus opt-in phones through libphonenumber-js.

Fits controlled inputs

Store raw in state and render formatted. The same call works in React, Vue, Svelte, vanilla JavaScript and server code.

Validation that stays in sync

The regex catalog pairs each pattern with its error message, including parametric rules for digits, phones, cards, URLs and passwords.

02 / Fit it into your stack

Two ways in. One format() call.

Every entrypoint exposes the same format() and regex. Pick the one that matches how your project loads JavaScript.

Package / ESM

@samline/formatter

ES module and CommonJS builds with bundled type declarations.

Explicit subpath

@samline/formatter/vanilla

The same API under a stable name for projects that pin a runtime subpath.

HTML / CDN

@samline/formatter/browser

A minified standalone script for pages without a bundler, including CMS themes.

Browser global

window.Formatter

The standalone script defines format, intl, regex, checks and version on one global.

Types

FormatOptions · FormatterResult

FormatType, RegexKey, DatePatternType and every option are exported.

Styles

No stylesheet

Nothing to import: the package returns strings and your CSS styles the field.

03 / From install to input

One field. Two clean values.

Format the visible input on every keystroke and mirror the raw value into a hidden input that your form submits.

Read the installation guide
1

Install

npm

Terminal
npm install @samline/formatter

pnpm

Terminal
pnpm add @samline/formatter

yarn

Terminal
yarn add @samline/formatter

bun

Terminal
bun add @samline/formatter

HTML / CDN

Terminal
<script src="https://cdn.jsdelivr.net/npm/@samline/formatter@3.3.1/dist/browser/formatter.phone.global.js" defer></script>
2

Add two inputs

A visible field for people and a hidden field with the name your backend reads.

index.html
<label for="phone">Mobile phone</label>
<input id="phone" type="text" inputmode="tel" autocomplete="tel" />
<input type="hidden" name="phone" />
3

Format on input

main.js
import { format } from '@samline/formatter'
import { registerPhone } from '@samline/formatter/phone'

registerPhone()

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
  hidden.value = raw
})
main.js
const { format } = window.Formatter

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
  hidden.value = raw
})

Load the CDN script from step 1 first, then this file with defer. window.Formatter replaces the import.

Copy complete working files

Continue with every option, the regex catalog and the TypeScript types.

Explore the configuration reference
04 / After the first field

Keep the display familiar.
Keep the data clean.

Patterns that come up in real forms: server-filled values, regional numbers, stored values and validation messages.

Edit forms

Show a value from your API

A stored ISO date has no display delimiter, so the default auto mode treats it as raw and converts it for display.

Read about interpretInputAs
edit-form.js
const { formatted } = format('1990-12-31', 'date', {
  datePattern: ['d', 'm', 'Y'],
  delimiter: '/',
  dateRawPattern: ['Y', 'm', 'd'],
  dateRawPatternDelimiter: '-',
})

field.value = formatted // '31/12/1990'
Numerals

Regional number formats

Swap the decimal mark and grouping delimiter for European amounts. The raw value always uses a dot.

Read the numeral options
amount.js
format('1234567,891', 'numeral', {
  numeralDecimalMark: ',',
  delimiter: '.',
  numeralDecimalScale: 2,
})
// { formatted: '1.234.567,89', raw: '1234567.89', type: 'numeral' }
Display

Display what you stored

Show stored amounts and dates in the reader’s locale with the Intl helpers. Empty or unreadable values return an empty string, never NaN.

Read about the Intl helpers
invoice.js
import { formatCurrency, formatDate } 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'
formatCurrency(null, { currency: 'MXN' }) // ''
Validation

Validate with the paired message

Test the raw value and show the message that belongs to the same rule through the native constraint API.

Explore the regex catalog
validate.js
import { format, regex } from '@samline/formatter'
import { registerPhone } from '@samline/formatter/phone'

registerPhone()

field.addEventListener('input', () => {
  const { formatted, raw } = format(field.value, 'phone')
  const rule = regex.phone({ length: 10 })
  field.value = formatted
  field.setCustomValidity(rule.pattern.test(raw) ? '' : rule.errorMessage)
})
Explore all twenty examples
05 / Before you build

A few details. Clearly answered.

Which value should my form submit?
Submit raw. It drops delimiters and decorations, keeps a leading + for international phones, uses a dot as the decimal mark and follows the raw date or time pattern. Keep formatted for display only: mirror raw into a hidden input, a form state field or the request body.
How do I show a value that is already stored?
Pass the stored raw value through format() and put formatted in the field. Dates and times use interpretInputAs: "auto" by default, so an ISO value such as 1990-12-31 is recognized as raw and converted to the display pattern. Use "raw" or "display" when your data is ambiguous.
What happens when people paste text?
Each call formats the whole value, so pasting works like typing. Phones ignore spaces, dashes and parentheses; card numbers and numerals drop separators; a pasted prefix or suffix that is already present is recognized instead of being added twice.
Does Formatter keep the caret position?
No. Formatter is a pure function and never reads the selection. Assigning the formatted value moves the caret to the end in most browsers, which suits fields typed from left to right. For editing in the middle, save selectionStart before formatting and restore an adjusted position with setSelectionRange(); the Styling and UX guide covers this.
Should I use type="number" or type="tel"?
Use type="text" with an inputmode hint (numeric, decimal or tel) and the matching autocomplete value. type="number" rejects separators, prefixes and suffixes, so the formatted value cannot be shown in it.
Does formatting validate the value?
No. Formatting shapes input; it does not decide whether it is correct. Pair it with the regex catalog, which gives each pattern a ready error message for setCustomValidity() or your own UI, and with the check-digit validators (isValidCard, isValidCurp, isValidIban and others) that catch mistyped digits. Always validate again on the server: a valid card number is not an authorized payment.
Which countries and regional formats are supported?
Phones use libphonenumber-js, so any ISO 3166-1 country code works, in upper or lower case; MX is the default. Numerals switch the decimal mark, grouping delimiter and currency position, and dates and times take any order of their segments.
Can I use it with React, Vue, Svelte or a CMS?
Yes. There is no adapter to install: call format() in the input handler you already have, store raw in state and render formatted. In Shopify or WordPress, load the CDN script once and attach listeners to your own fields. The framework guide has complete controlled-input examples.
Can I run it on the server?
Yes. format() has no DOM access or timers, and its only module state is the one-time registerPhone() switch, so it runs in Node.js 20+, workers and tests with the same output. Use it to normalize imported data, render formatted values in emails, or re-check what a form submitted.
How large is it?
The core is about 16 KB minified (6 KB gzip) when you import only format, and about 32 KB with every validator with a bundler and has no runtime dependency. Phone support is opt-in: @samline/formatter/phone adds libphonenumber-js (about 143 KB minified). The browser scripts are about 36 KB without phones and 174 KB with them.
What happens with empty or invalid input?
null, undefined and empty strings return empty formatted and raw values. An unknown format type throws a TypeError, and a general mask without blocks throws a descriptive error; use isFormatType() to check a type that comes from configuration or a URL.
Is upgrading from 2.x safe?
3.0.0 makes phones opt-in: call registerPhone() from @samline/formatter/phone, or load formatter.phone.global.js instead of the renamed browser script. Every other format keeps its output. Read the changelog migration notes before you upgrade.
A little structure goes a long way

Make every field a clean one.

Try a working field or format your first input.

Installation, practical guides and the complete API for Formatter 3.3.1.

Read the documentation