Functional Weave
Code in Python

react.form.money-field@1.0.0

README.md

2,374 bytes · view raw

# react.form.money-field

An amount of money in one known currency, typed the way the person's locale
writes numbers, read as integer minor units by `form.money-input`. It is
`react.form.text-field` with the currency symbol as a prefix (or a suffix,
for currencies written after the amount), a decimal keyboard and no spell
check.

```tsx
"use client";
import { MoneyField } from "#fune/react.form.money-field@^1";
import { parseMoneyInput, formatMoneyInput } from "#fune/form.money-input@^1";

const rules = { label: "Amount", required: true, min: 100, max: 1000000, allowNegative: false };
<MoneyField id="amount" label="How much do you want to send, in pounds?" currency="GBP" locale="en-GB"
  rules={rules} hint="For example, 1,234.50" value={text} onChange={setText} showError={submitted} />

// On submit, in the browser or on the server:
const check = parseMoneyInput(text, "GBP", "en-GB", rules); // check.amount = { minor: 123450, currency: "GBP" }
// To edit a stored amount: setText(formatMoneyInput(stored, "en-GB"))  // "1,234.50"
```

- **Never a float.** The text becomes `Money { minor, currency }` with
  `money.parse`'s strict rules: grouping must be real thousands, no more
  decimal places than the currency has (none for JPY), and a symbol typed in
  must be this currency's.
- **Locale.** `de-DE` reads `1.234,50`, `fr-FR` `1 234,50`, `de-CH`
  `1'234.50`; `formatMoneyInput` writes an amount back the same way. Which
  side the symbol goes is the currency's, from `money.format`'s table (kr
  after, £ € ¥ before), not the locale's: a French page shows € as a prefix.
- **Accessible.** The symbol is `aria-hidden`, as GOV.UK does, so say the
  currency in the label. Errors use `aria-describedby` and `aria-invalid`
  through `react.form.text-field`.
- `showError` turns the check on; `error` shows another message instead. An
  unknown currency or locale throws: it is a bug in the page.

It is a client component. Classes: those of `react.form.text-field`, plus
`fune-money-field` on the wrapper.

Sources: GOV.UK Design System, "Text input" (prefixes and suffixes)
https://design-system.service.gov.uk/components/text-input/ .

## Notices

Portions derived from GOV.UK Frontend (https://github.com/alphagov/govuk-frontend), Copyright (c) 2017 Crown Copyright (Government Digital Service), under the MIT License; the full notice is in NOTICE.