Functional Weave
Code in Rust

form.money-input

Read a typed amount as minor units for its currency and locale, check min/max, and format it back.

1.0.0 · published 2026-10-10 by charlie · Anterra

Pinned by 61 tests, run in TypeScript, Python and Rust.parseMoneyInput 37 · formatMoneyInput 13 · moneyInputFormat 11

What it does

The logic behind a money input: read what was typed as integer minor units, check it, and write an amount back for editing, the same way in the browser (`react.form.money-field` calls it) and on the server (TypeScript, Python or Rust), so both refuse the same text with the same words.

parseMoneyInput("£1,234.50", "GBP", "en-GB", { label: "Monthly rent", required: true, min: 1000, max: 500000, allowNegative: false });
// { valid: true, amount: { minor: 123450, currency: "GBP" }, message: null }

parseMoneyInput("1,234.50", "EUR", "de-DE", { label: "Amount", required: true, min: null, max: null, allowNegative: false });
// { valid: false, amount: null, message: "Enter amount in the correct format, like 1.234,50" }

formatMoneyInput({ minor: 123450, currency: "EUR" }, "fr-FR");   // "1 234,50"
moneyInputFormat("SEK", "sv-SE");
// { currency: "SEK", symbol: "kr", symbolBefore: false, digits: 2, groupSeparator: " ", decimalSeparator: ",", example: "1 234,50" }

The functions

A group: 3 functions that work together, each in its own file, each pinned by its own tests in TypeScript, Python and Rust. A project can install only the ones it calls.

  1. parse_money_input (text: string, currency: string, locale: string, rules: MoneyRules) -> MoneyInputCheck
  2. format_money_input (amount: Money, locale: string) -> string
  3. money_input_format (currency: string, locale: string) -> MoneyInputFormat

The types it declares, generated into your project

/// What a money input requires.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MoneyRules {
    /// what the amount is, as it starts a sentence: "Amount", "Monthly rent"
    pub label: String,
    /// an empty value is an error
    pub required: bool,
    /// the smallest amount allowed, in minor units
    pub min: Option<i64>,
    /// the largest amount allowed, in minor units
    pub max: Option<i64>,
    /// a leading minus is accepted
    pub allow_negative: bool,
}

/// The verdict on a money input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MoneyInputCheck {
    pub valid: bool,
    /// the amount, when valid and given
    pub amount: Option<Money>,
    /// the error message to show, when not valid
    pub message: Option<String>,
}

/// How a money input for a currency and locale looks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MoneyInputFormat {
    /// the ISO code
    pub currency: String,
    /// the symbol to show beside the input, such as £ or €
    pub symbol: String,
    /// the symbol goes before the amount (a prefix) rather than after (a suffix)
    pub symbol_before: bool,
    /// decimal places in the minor unit: 2 for GBP, 0 for JPY
    pub digits: i64,
    /// what groups thousands in this locale
    pub group_separator: String,
    /// what marks the decimal in this locale
    pub decimal_separator: String,
    /// 1234.50 written this way, for a hint: "1,234.50"
    pub example: String,
}

Once installed, your code imports each one from the group's module.

parse_money_input throws on bad input 37 tests

pub fn parse_money_input(text: &str, currency: &str, locale: &str, rules: &MoneyRules) -> MoneyInputCheck
textstringwhat was typed: "1,234.50", "£12", "1.234,50" for de-DE; untrimmed
currencystringISO 4217 code; a symbol typed in the text must be this currency's
localestringBCP 47 locale (en-GB, de-DE, fr-FR...) that says how digits are grouped and the decimal marked
rulesMoneyRulesthe label, required, and optional bounds in minor units
returnsMoneyInputCheckvalid with the Money, or the message

For example

  • parse_money_input(1,234.50, GBP, en-GB, label Amount, required true, min —, max —, allow negative false) → valid true, amount £1,234.50, message — grouped pounds and pence
  • parse_money_input(£1,234.50, GBP, en-GB, label Amount, required true, min —, max —, allow negative false) → valid true, amount £1,234.50, message — the pound sign typed before it
  • parse_money_input( £12 , GBP, en-GB, label Amount, required true, min —, max —, allow negative false) → valid true, amount £12.00, message — spaces and a trailing newline are trimmed
fune!(form.money-input@^1);  // then call parse_money_input(…)
impl/rust/parse_money_input.rs · 223 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::form_money_input_format_money_input::{number_style_for, separators_of};  ← formatMoneyInput, another function of this group · built into the same file, even by a slim install
use super::form_money_input_money_input_format::{money_for_message, money_input_format};  ← moneyInputFormat, another function of this group · built into the same file, even by a slim install
use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::money_amount::money_to_value;  ← from money.amount ^1.0.0 · built alongside by fune
use super::money_currency_digits::currency_digits;  ← from money.currency-digits ^1.0.0 · built alongside by fune
use super::money_currency_digits_data::CURRENCY_DIGITS;  ← money.currency-digits’s rule data (^1.0.0) · built alongside by fune
use super::money_format_data::CURRENCIES;  ← money.format’s rule data (^1.0.0) · built alongside by fune
use super::money_parse::parse_money;  ← from money.parse ^1.0.0 · built alongside by fune
use super::money_parse_data::CURRENCY_SYMBOLS;  ← money.parse’s rule data (^1.0.0) · built alongside by fune

const MAX_SAFE: &str = "9007199254740991";
// The spaces money.parse allows between a symbol and the number.
const SPACES: &[char] = &[' ', '\u{a0}', '\u{202f}'];

// ASCII whitespace only, so all three languages trim the same characters.
fn trim_ascii(value: &str) -> &str {
    value.trim_matches(|c: char| matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0c' | '\x0b'))
}

fn is_digits(value: &str) -> bool {
    !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit())
}

fn lower_first(label: &str) -> String {
    let bytes = label.as_bytes();
    let upper = |i: usize| i < bytes.len() && bytes[i].is_ascii_uppercase();
    if upper(0) && !upper(1) {
        let mut out = String::with_capacity(label.len());
        out.push(bytes[0].to_ascii_lowercase() as char);
        out.push_str(&label[1..]);
        out
    } else {
        label.to_string()
    }
}

/// The longest known symbol or ISO code `matches` accepts, compared in characters.
fn longest_symbol(matches: impl Fn(&str) -> bool) -> Option<&'static str> {
    let mut best: Option<&'static str> = None;
    let candidates = CURRENCY_SYMBOLS.iter().map(|r| r.symbol).chain(CURRENCY_DIGITS.iter().map(|r| r.code));
    for symbol in candidates {
        let longer = match best {
            None => true,
            Some(b) => symbol.chars().count() > b.chars().count(),
        };
        if matches(symbol) && longer {
            best = Some(symbol);
        }
    }
    best
}

fn split_number(s: &str, groups: &[char], decimal: char) -> Option<(String, String)> {
    let parts: Vec<&str> = s.split(decimal).collect();
    if parts.len() > 2 {
        return None;
    }
    let fraction = if parts.len() == 2 { parts[1] } else { "" };
    if parts.len() == 2 && !is_digits(fraction) {
        return None;
    }
    let chunks: Vec<&str> = parts[0].split(|c: char| groups.contains(&c)).collect();
    if !chunks.iter().all(|c| is_digits(c)) {
        return None;
    }
    if chunks.len() > 1 {
        let first = chunks[0];
        if first.len() > 3 || first.starts_with('0') {
            return None;
        }
        if !chunks[1..].iter().all(|c| c.len() == 3) {
            return None;
        }
    }
    Some((chunks.concat(), fraction.to_string()))
}

fn invalid(message: String) -> MoneyInputCheck {
    MoneyInputCheck { valid: false, amount: None, message: Some(message) }
}

/// An amount typed into a money input, read as integer minor units: the shape
/// checked here, with a message for each way it can be wrong, so that
/// money.parse only ever converts text it accepts; then the bounds.
///
/// # Panics
/// Panics on an empty label, an unknown currency or locale, or min above max.
pub fn parse_money_input(text: &str, currency: &str, locale: &str, rules: &MoneyRules) -> MoneyInputCheck {
    let label = trim_ascii(&rules.label);
    if label.is_empty() {
        panic!("a money input needs a label, such as \"Amount\", to write its error messages");
    }
    let digits = currency_digits(currency);
    let style = number_style_for(locale);
    if let (Some(lo), Some(hi)) = (rules.min, rules.max) {
        if lo > hi {
            panic!("rules.min ({}) must not be more than rules.max ({})", lo, hi);
        }
    }
    let seps = separators_of(style);

    let mut s: &str = trim_ascii(text);
    if s.is_empty() {
        if rules.required {
            return invalid(format!("Enter {}", lower_first(label)));
        }
        return MoneyInputCheck { valid: true, amount: None, message: None };
    }
    let shape = format!("Enter {} in the correct format, like {}", lower_first(label), money_input_format(currency, locale).example);

    let mut negative = false;
    if let Some(rest) = s.strip_prefix('-') {
        negative = true;
        s = rest;
    }
    let mut symbol = longest_symbol(|k| s.starts_with(k));
    if let Some(sym) = symbol {
        s = &s[sym.len()..];
        if let Some(rest) = s.strip_prefix(SPACES) {
            s = rest;
        }
        if !negative {
            if let Some(rest) = s.strip_prefix('-') {
                negative = true;
                s = rest;
            }
        }
    } else {
        symbol = longest_symbol(|k| s.ends_with(k));
        if let Some(sym) = symbol {
            s = &s[..s.len() - sym.len()];
            if let Some(rest) = s.strip_suffix(SPACES) {
                s = rest;
            }
        }
    }
    let own = match symbol {
        None => true,
        Some(sym) => {
            sym == currency
                || CURRENCY_SYMBOLS.iter().any(|r| r.code == currency && r.symbol == sym)
                || CURRENCIES.iter().any(|r| r.code == currency && r.symbol.trim_matches(' ') == sym)
        }
    };
    if !own {
        return invalid(shape);
    }

    let (whole, fraction) = match split_number(s, seps.groups, seps.decimal) {
        Some(found) => found,
        None => return invalid(shape),
    };
    if negative && !rules.allow_negative {
        return invalid(format!("{} must not be negative", label));
    }
    if fraction.len() as i64 > digits {
        if digits == 0 {
            return invalid(format!("{} must be a whole number", label));
        }
        let unit = if digits == 1 { "place" } else { "places" };
        return invalid(format!("{} must not have more than {} decimal {}", label, digits, unit));
    }
    let mut padded = fraction.clone();
    while (padded.len() as i64) < digits {
        padded.push('0');
    }
    let joined = format!("{}{}", whole, padded);
    let all = joined.trim_start_matches('0');
    if all.len() > MAX_SAFE.len() || (all.len() == MAX_SAFE.len() && all > MAX_SAFE) {
        return invalid(format!("{} is too large", label));
    }

    let canonical = format!(
        "{}{}{}",
        if negative { "-" } else { "" },
        whole,
        if fraction.is_empty() { String::new() } else { format!("{}{}", seps.decimal, fraction) }
    );
    let amount = parse_money(&canonical, currency, style);
    match (rules.min, rules.max) {
        (Some(lo), Some(hi)) if amount.minor < lo || amount.minor > hi => {
            return invalid(format!(
                "{} must be between {} and {}",
                label,
                money_for_message(lo, currency, locale),
                money_for_message(hi, currency, locale)
            ));
        }
        (Some(lo), None) if amount.minor < lo => {
            return invalid(format!("{} must be {} or more", label, money_for_message(lo, currency, locale)));
        }
        (None, Some(hi)) if amount.minor > hi => {
            return invalid(format!("{} must be {} or less", label, money_for_message(hi, currency, locale)));
        }
        _ => {}
    }
    MoneyInputCheck { valid: true, amount: Some(amount), message: None }
}

pub fn money_input_check_to_value(check: &MoneyInputCheck) -> Value {
    Value::obj(vec![
        ("valid", Value::Bool(check.valid)),
        ("amount", check.amount.as_ref().map(money_to_value).unwrap_or(Value::Null)),
        ("message", check.message.as_deref().map(Value::str).unwrap_or(Value::Null)),
    ])
}

pub fn fune_vector(args: &[Value]) -> Value {
    let r = &args[3];
    let int = |key: &str| match r.get(key) {
        Value::Int(n) => Some(*n),
        Value::Null => None,
        other => panic!("rules.{} must be a whole number of minor units, got {:?}", key, other),
    };
    let rules = MoneyRules {
        label: r.get("label").as_str().to_string(),
        required: r.get("required").as_bool(),
        min: int("min"),
        max: int("max"),
        allow_negative: r.get("allowNegative").as_bool(),
    };
    money_input_check_to_value(&parse_money_input(args[0].as_str(), args[1].as_str(), args[2].as_str(), &rules))
}

format_money_input throws on bad input 13 tests

pub fn format_money_input(amount: &Money, locale: &str) -> String
amountMoneythe amount to put back into the input for editing
localestringhow to group digits and mark the decimal
returnsstringdigits with grouping and every decimal place, no symbol: "1,234.50", "1.234,50", "-0.05"

For example

  • format_money_input(£1,234.50, en-GB) → 1,234.50 pounds and pence
  • format_money_input(€1,234.50, de-DE) → 1.234,50 German
  • format_money_input(€1,234.50, fr-FR) → 1 234,50 French, with a plain space to type
fune!(form.money-input@^1);  // then call format_money_input(…)
impl/rust/format_money_input.rs · 82 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::form_money_input_data::LOCALES;  ← this capability’s own data, compiled from data/locales.json into the same file by fune build
use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::money_amount::{money_from_value, Money};  ← from money.amount ^1.0.0 · built alongside by fune
use super::money_currency_digits::currency_digits;  ← from money.currency-digits ^1.0.0 · built alongside by fune

/// The separators of a money.parse number style, as money.parse reads them.
pub struct NumberSeparators {
    /// Every group separator money.parse accepts in this style.
    pub groups: &'static [char],
    /// The one this capability writes.
    pub group: &'static str,
    pub decimal: char,
}

/// The money.parse number style for a locale: the exact locale first
/// (case-insensitive, "_" read as "-"), then its language alone.
///
/// # Panics
/// Panics on a locale it does not list.
pub fn number_style_for(locale: &str) -> &'static str {
    let wanted = locale.replace('_', "-").to_ascii_lowercase();
    if let Some(row) = LOCALES.iter().find(|r| r.locale.to_ascii_lowercase() == wanted) {
        return row.style;
    }
    let language = wanted.split('-').next().unwrap_or("");
    if !language.is_empty() {
        if let Some(row) = LOCALES.iter().find(|r| r.locale.to_ascii_lowercase() == language) {
            return row.style;
        }
    }
    panic!("unknown locale \"{}\": give a BCP 47 locale this capability lists, such as en-GB, de-DE or fr-FR", locale);
}

/// # Panics
/// Panics on an unknown style.
pub fn separators_of(style: &str) -> NumberSeparators {
    match style {
        "comma-dot" => NumberSeparators { groups: &[','], group: ",", decimal: '.' },
        "dot-comma" => NumberSeparators { groups: &['.'], group: ".", decimal: ',' },
        "space-comma" => NumberSeparators { groups: &[' ', '\u{a0}', '\u{202f}'], group: " ", decimal: ',' },
        "apostrophe-dot" => NumberSeparators { groups: &['\'', '\u{2019}'], group: "'", decimal: '.' },
        other => panic!("unknown number style \"{}\"", other),
    }
}

/// Minor units written with thousands grouping and every decimal place, no symbol.
pub fn write_amount(minor: i64, digits: i64, style: &str) -> String {
    let seps = separators_of(style);
    let digits = digits as usize;
    let mut raw = minor.unsigned_abs().to_string();
    while raw.len() < digits + 1 {
        raw.insert(0, '0');
    }
    let (whole, fraction) = raw.split_at(raw.len() - digits);
    let mut grouped = String::new();
    for (i, ch) in whole.chars().enumerate() {
        if i > 0 && (whole.len() - i) % 3 == 0 {
            grouped.push_str(seps.group);
        }
        grouped.push(ch);
    }
    let number = if digits > 0 { format!("{}{}{}", grouped, seps.decimal, fraction) } else { grouped };
    if minor < 0 {
        format!("-{}", number)
    } else {
        number
    }
}

/// An amount as a money input shows it for editing: the locale's grouping and
/// decimal mark, every decimal place, no symbol.
///
/// # Panics
/// Panics on an unknown currency or locale.
pub fn format_money_input(amount: &Money, locale: &str) -> String {
    let digits = currency_digits(&amount.currency);
    write_amount(amount.minor, digits, number_style_for(locale))
}

pub fn fune_vector(args: &[Value]) -> Value {
    Value::str(&format_money_input(&money_from_value(&args[0]), args[1].as_str()))
}

money_input_format throws on bad input 11 tests

pub fn money_input_format(currency: &str, locale: &str) -> MoneyInputFormat
currencystringISO 4217 code
localestringBCP 47 locale
returnsMoneyInputFormatwhat a money input shows: the symbol, separators and an example

For example

  • money_input_format(GBP, en-GB) → currency GBP, symbol £, symbol before true, digits 2, group separator ,, decimal separator ., example 1,234.50 pounds in the UK
  • money_input_format(EUR, de-DE) → currency EUR, symbol €, symbol before true, digits 2, group separator ., decimal separator ,, example 1.234,50 euros in Germany
  • money_input_format(SEK, sv-SE) → currency SEK, symbol kr, symbol before false, digits 2, group separator , decimal separator ,, example 1 234,50 kronor in Sweden: the symbol goes after
fune!(form.money-input@^1);  // then call money_input_format(…)
impl/rust/money_input_format.rs · 80 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::form_money_input_format_money_input::{number_style_for, separators_of, write_amount};  ← formatMoneyInput, another function of this group · built into the same file, even by a slim install
use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::money_currency_digits::currency_digits;  ← from money.currency-digits ^1.0.0 · built alongside by fune
use super::money_format_data::CURRENCIES;  ← money.format’s rule data (^1.0.0) · built alongside by fune
use super::money_parse_data::CURRENCY_SYMBOLS;  ← money.parse’s rule data (^1.0.0) · built alongside by fune

/// A currency's symbol: `raw` keeps money.format's spacing ("CHF ", " kr").
pub struct CurrencySymbol {
    pub symbol: String,
    pub raw: String,
    pub before: bool,
}

/// money.format's symbol where it has the currency, else the first symbol
/// money.parse knows (before the amount), else the ISO code itself.
pub fn currency_symbol(currency: &str) -> CurrencySymbol {
    if let Some(row) = CURRENCIES.iter().find(|r| r.code == currency) {
        return CurrencySymbol { symbol: row.symbol.trim_matches(' ').to_string(), raw: row.symbol.to_string(), before: row.symbol_before };
    }
    if let Some(row) = CURRENCY_SYMBOLS.iter().find(|r| r.code == currency) {
        return CurrencySymbol { symbol: row.symbol.to_string(), raw: row.symbol.to_string(), before: true };
    }
    CurrencySymbol { symbol: currency.to_string(), raw: format!("{} ", currency), before: true }
}

/// An amount in a sentence: "£10.00", "100,00 kr", "€1.000,00".
pub fn money_for_message(minor: i64, currency: &str, locale: &str) -> String {
    let digits = currency_digits(currency);
    let sym = currency_symbol(currency);
    let number = write_amount(minor.abs(), digits, number_style_for(locale));
    let body = if sym.before { format!("{}{}", sym.raw, number) } else { format!("{}{}", number, sym.raw) };
    if minor < 0 {
        format!("-{}", body)
    } else {
        body
    }
}

/// What a money input for this currency and locale shows: the symbol, the
/// separators, and 1234.50 written the locale's way.
///
/// # Panics
/// Panics on an unknown currency or locale.
pub fn money_input_format(currency: &str, locale: &str) -> MoneyInputFormat {
    let digits = currency_digits(currency);
    let style = number_style_for(locale);
    let seps = separators_of(style);
    let sym = currency_symbol(currency);
    let mut fraction = String::from("50");
    while fraction.len() < digits as usize {
        fraction.push('0');
    }
    fraction.truncate(digits as usize);
    let example: i64 = format!("1234{}", fraction).parse().unwrap_or(1234);
    MoneyInputFormat {
        currency: currency.to_string(),
        symbol: sym.symbol,
        symbol_before: sym.before,
        digits,
        group_separator: seps.group.to_string(),
        decimal_separator: seps.decimal.to_string(),
        example: write_amount(example, digits, style),
    }
}

pub fn money_input_format_to_value(f: &MoneyInputFormat) -> Value {
    Value::obj(vec![
        ("currency", Value::str(&f.currency)),
        ("symbol", Value::str(&f.symbol)),
        ("symbolBefore", Value::Bool(f.symbol_before)),
        ("digits", Value::Int(f.digits)),
        ("groupSeparator", Value::str(&f.group_separator)),
        ("decimalSeparator", Value::str(&f.decimal_separator)),
        ("example", Value::str(&f.example)),
    ])
}

pub fn fune_vector(args: &[Value]) -> Value {
    money_input_format_to_value(&money_input_format(args[0].as_str(), args[1].as_str()))
}

Install

fune build

With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and its 4 dependencies, pins them in fune.lock, downloads only the Rust package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. A crate’s build.rs runs it before every compile. Or pin a range in fune.project and build in one step:

fune add form.money-input

That builds the whole group. To build only what you call, and whatever it uses inside the group:

fune add form.money-input --only parseMoneyInput
Download for Rust form.money-input-1.0.0-rust.fune · 47,492 bytes sha256 f33fa9a172e2fc6ae16c3e38b4f1a94ff9c52653dce11d829a097c28eb7ca3e3

The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./form.money-input-1.0.0-rust.fune, or fetch it from a terminal with fune pull form.money-input@1.0.0:rust.

The whole function, every language, is one file too: form.money-input-1.0.0.fune, 71,173 bytes, sha256 c6e008a8d83dc36f54bfae7d3b176420ea843ee74067b2f46591a6408f12ed42. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

// fune: before form.money-input.parseMoneyInput
// fune: before form.money-input.formatMoneyInput
// fune: before form.money-input.moneyInputFormat

after — your function gets the result and the arguments, and returns the final result.

// fune: after form.money-input.parseMoneyInput
// fune: after form.money-input.formatMoneyInput
// fune: after form.money-input.moneyInputFormat

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

// fune: replace money.amount in form.money-input
// fune: replace money.currency-digits in form.money-input
// fune: replace money.format in form.money-input
// fune: replace money.parse in form.money-input

step — your function runs at a numbered point inside a function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show form.money-input --steps.

// fune: step form.money-input.<fn> after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

parseMoneyInput 37 tests

CaseArgumentsExpected
grouped pounds and pence 1,234.50, GBP, en-GB, label Amount, required true, min —, max —, allow negative false → valid true, amount £1,234.50, message —
the pound sign typed before it £1,234.50, GBP, en-GB, label Amount, required true, min —, max —, allow negative false → valid true, amount £1,234.50, message —
spaces and a trailing newline are trimmed £12 , GBP, en-GB, label Amount, required true, min —, max —, allow negative false → valid true, amount £12.00, message —
one decimal place is enough: 1234.5 is £1,234.50 1234.5, GBP, en-GB, label Amount, required true, min —, max —, allow negative false → valid true, amount £1,234.50, message —
German grouping and decimal comma 1.234,50, EUR, de-DE, label Amount, required true, min —, max —, allow negative false → valid true, amount €1,234.50, message —
French spaces and a trailing euro sign 1 234,50 €, EUR, fr-FR, label Amount, required true, min —, max —, allow negative false → valid true, amount €1,234.50, message —
Swiss apostrophes 1'234.50, CHF, de-CH, label Amount, required true, min —, max —, allow negative false → valid true, amount 1,234.50 CHF, message —
Swedish kronor written after the amount 100 kr, SEK, sv-SE, label Amount, required true, min —, max —, allow negative false → valid true, amount 100.00 SEK, message —
the ISO code typed as the symbol GBP 12, GBP, en-GB, label Amount, required true, min —, max —, allow negative false → valid true, amount £12.00, message —
yen have no decimal places 1,500, JPY, ja-JP, label Amount, required true, min —, max —, allow negative false → valid true, amount ¥1,500, message —
Show the other 27 tests
CaseArgumentsExpected
Kuwaiti dinar have three 1.5, KWD, en-GB, label Amount, required true, min —, max —, allow negative false → valid true, amount 1.500 KWD, message —
a locale's language alone, and an underscore 1.234,50, EUR, de_AT, label Amount, required true, min —, max —, allow negative false → valid true, amount €1,234.50, message —
nothing typed in a required input , GBP, en-GB, label Monthly rent, required true, min —, max —, allow negative false → valid false, amount —, message Enter monthly rent
nothing typed in an optional input is valid, with no amount , GBP, en-GB, label Amount, required false, min —, max —, allow negative false → valid true, amount —, message —
another currency's symbol $12, GBP, en-GB, label Amount, required true, min —, max —, allow negative false → valid false, amount —, message Enter amount in the correct format, like 1,234.50
English grouping in a German input is wrong, and the example says how 1,234.50, EUR, de-DE, label Amount, required true, min —, max —, allow negative false → valid false, amount —, message Enter amount in the correct format, like 1.234,50
grouping that is not thousands 1,23.45, GBP, en-GB, label Amount, required true, min —, max —, allow negative false → valid false, amount —, message Enter amount in the correct format, like 1,234.50
Arabic-Indic digits are not an amount ١٢, GBP, en-GB, label Amount, required true, min —, max —, allow negative false → valid false, amount —, message Enter amount in the correct format, like 1,234.50
letters twelve, GBP, en-GB, label Amount, required true, min —, max —, allow negative false → valid false, amount —, message Enter amount in the correct format, like 1,234.50
too many decimal places 12.345, GBP, en-GB, label Amount, required true, min —, max —, allow negative false → valid false, amount —, message Amount must not have more than 2 decimal places
decimals in a currency without them 1500.5, JPY, ja-JP, label Amount, required true, min —, max —, allow negative false → valid false, amount —, message Amount must be a whole number
a minus where negatives are not allowed -5, GBP, en-GB, label Amount, required true, min —, max —, allow negative false → valid false, amount —, message Amount must not be negative
a refund may be negative, the minus before the symbol -£5.00, GBP, en-GB, label Amount, required true, min —, max —, allow negative true → valid true, amount -£5.00, message —
the minus after the symbol £-0.05, GBP, en-GB, label Amount, required true, min —, max —, allow negative true → valid true, amount -£0.05, message —
the largest amount money holds exactly 90071992547409.91, GBP, en-GB, label Amount, required true, min —, max —, allow negative false → valid true, amount £90,071,992,547,409.91, message —
one penny more is too large 90071992547409.92, GBP, en-GB, label Amount, required true, min —, max —, allow negative false → valid false, amount —, message Amount is too large
below the range, both bounds in the message 5, GBP, en-GB, label Monthly rent, required true, min 1,000, max 100,000, allow negative false → valid false, amount —, message Monthly rent must be between £10.00 and £1,000.00
exactly the minimum is allowed 10, GBP, en-GB, label Amount, required true, min 1,000, max 100,000, allow negative false → valid true, amount £10.00, message —
a minimum only 5, GBP, en-GB, label Amount, required true, min 1,000, max —, allow negative false → valid false, amount —, message Amount must be £10.00 or more
a maximum only, the bound written the German way 2.000, EUR, de-DE, label Amount, required true, min —, max 100,000, allow negative false → valid false, amount —, message Amount must be €1.000,00 or less
a bound in kronor, symbol after 5, SEK, sv-SE, label Amount, required true, min 10,000, max —, allow negative false → valid false, amount —, message Amount must be 100,00 kr or more
a currency money.format has no symbol for is named by its code 1, BHD, en-GB, label Amount, required true, min 10,000, max —, allow negative false → valid false, amount —, message Amount must be BHD 10.000 or more
an acronym label keeps its capital , GBP, en-GB, label VAT amount, required true, min —, max —, allow negative false → valid false, amount —, message Enter VAT amount
an unknown locale 1, GBP, xx-YY, label Amount, required true, min —, max —, allow negative false → error: unknown locale "xx-YY"
an unknown currency 1, ABC, en-GB, label Amount, required true, min —, max —, allow negative false → error: no ISO 4217 minor unit for currency "ABC"
min above max 1, GBP, en-GB, label Amount, required true, min 500, max 100, allow negative false → error: rules.min (500) must not be more than rules.max (100)
an empty label 1, GBP, en-GB, label , required true, min —, max —, allow negative false → error: a money input needs a label

formatMoneyInput 13 tests

CaseArgumentsExpected
pounds and pence £1,234.50, en-GB → 1,234.50
German €1,234.50, de-DE → 1.234,50
French, with a plain space to type €1,234.50, fr-FR → 1 234,50
Swiss 1,234.50 CHF, de-CH → 1'234.50
a negative penny -£0.05, en-GB → -0.05
zero keeps its decimals £0.00, en-GB → 0.00
yen: no decimal mark ¥1,500, ja-JP → 1,500
three decimal places 1,234.567 KWD, en-GB → 1,234.567
a million dollars $1,000,000.00, en-US → 1,000,000.00
a language alone £9.99, en → 9.99
Show the other 3 tests
CaseArgumentsExpected
the largest exact amount £90,071,992,547,409.91, en-GB → 90,071,992,547,409.91
an unknown locale £0.01, tlh → error: unknown locale "tlh"
an unknown currency 0.01 ABC, en-GB → error: no ISO 4217 minor unit for currency "ABC"

moneyInputFormat 11 tests

CaseArgumentsExpected
pounds in the UK GBP, en-GB → currency GBP, symbol £, symbol before true, digits 2, group separator ,, decimal separator ., example 1,234.50
euros in Germany EUR, de-DE → currency EUR, symbol €, symbol before true, digits 2, group separator ., decimal separator ,, example 1.234,50
kronor in Sweden: the symbol goes after SEK, sv-SE → currency SEK, symbol kr, symbol before false, digits 2, group separator , decimal separator ,, example 1 234,50
francs in Switzerland: the symbol trimmed for the prefix CHF, de-CH → currency CHF, symbol CHF, symbol before true, digits 2, group separator ', decimal separator ., example 1'234.50
yen: no decimals in the example JPY, ja-JP → currency JPY, symbol ¥, symbol before true, digits 0, group separator ,, decimal separator ., example 1,234
Kuwaiti dinar: three KWD, en-GB → currency KWD, symbol KD, symbol before true, digits 3, group separator ,, decimal separator ., example 1,234.500
Canadian dollars: money.parse's first symbol CAD, en-CA → currency CAD, symbol $, symbol before true, digits 2, group separator ,, decimal separator ., example 1,234.50
Bahraini dinar: no symbol known, so the code BHD, en-GB → currency BHD, symbol BHD, symbol before true, digits 3, group separator ,, decimal separator ., example 1,234.500
euros in France EUR, fr-FR → currency EUR, symbol €, symbol before true, digits 2, group separator , decimal separator ,, example 1 234,50
an unknown locale GBP, → error: unknown locale ""
Show the other 1 test
CaseArgumentsExpected
an unknown currency gbp, en-GB → error: no ISO 4217 minor unit for currency "gbp"

Verification

Verified by the operator, not the sandbox 61 test vectors declared; none run by the registry.

Verified locally by the registry's operator, not by the sandbox. This version was published with FUNE_VERIFY_MODE=inline-dev (the operator's import of the first-party registry, or a development server): the server validated the package - its manifest, signatures, imports, safety lint and test rules - but the registry did not run its test vectors in its sandbox. The operator runs them with `fune verify --all` before importing.

Signed by the registry with key fw-9dc887227da47575 (ed25519), over its integrity and this report's digest. The full report · JSON

More from the author

## Built on money.*

- **money.parse** does the conversion to minor units. It is strict and throws; a form wants a message instead, so this capability checks the shape first, with money.parse's own rules (symbol before or after, at most one space beside it, a minus before or after a leading symbol, real thousands grouping or none), and hands money.parse only text it is certain to accept. - **money.currency-digits** says how many decimal places a currency has (2 for GBP, 0 for JPY, 3 for KWD). Unknown currencies throw its error. - **money.format**'s currency table gives the symbol and which side it goes on; for a currency it does not list, the first symbol money.parse knows for it (put before), else the ISO code. Amounts in messages are written with that symbol and the locale's separators: "£10.00", "€1.000,00", "100,00 kr".

## Locales

`locale` picks money.parse's number style from `data/locales.json`: the exact locale first (case-insensitive, `_` read as `-`), then its language alone (`de-AT` is listed; `de-LU` falls back to `de`). An unlisted locale throws `unknown locale`. The styles are comma-dot (en, ja, zh, ko, he, th), dot-comma (de, es, it, nl, pt-BR, da, id, tr, el), space-comma (fr, pt-PT, sv, nb, fi, pl, cs, sk, hu, ru, uk) and apostrophe-dot (de-CH, it-CH, de-LI).

Only thousands grouping is read and written: en-IN's lakh grouping (12,34,567.00) is refused as typed, though the ungrouped number is accepted. `formatMoneyInput` groups with a plain space in space-comma locales (what a keyboard types); money.parse also reads the no-break spaces documents use.

## The checks, in order, and their messages

| Typed | Message | |---|---| | nothing, `required` | Enter monthly rent | | not an amount in this locale, or another currency's symbol | Enter monthly rent in the correct format, like 1,234.50 | | a minus, without `allowNegative` | Monthly rent must not be negative | | too many decimals | Monthly rent must not have more than 2 decimal places | | decimals for a currency without them | Monthly rent must be a whole number | | more than 2^53 - 1 minor units | Monthly rent is too large | | outside `min`..`max` (minor units, inclusive) | Monthly rent must be between £10.00 and £5,000.00 / must be £10.00 or more / must be £5,000.00 or less |

Text is trimmed of ASCII whitespace; digits are ASCII only, so "١٢" is not an amount. Nothing typed in an optional input is valid with `amount` null. The label starts the sentence ("Monthly rent must ..."), and after "Enter" its first letter is lower-cased unless it starts an acronym ("Enter VAT amount").

The example in `moneyInputFormat` and in the format message is 1234.50 with as many decimal places as the currency has: "1,234" for yen, "1,234.500" for Kuwaiti dinar.

## Errors

Thrown, since they are the caller's: an empty label, an unknown currency or locale, `min` above `max`.

Files

PathBytes
README.md3,904
data/locales.json3,049
impl/python/format_money_input.py2,532
impl/python/money_input_format.py2,097
impl/python/parse_money_input.py5,872
impl/rust/format_money_input.rs3,168
impl/rust/money_input_format.rs3,229
impl/rust/parse_money_input.rs8,210
impl/typescript/format_money_input.ts2,993
impl/typescript/money_input_format.ts2,562
impl/typescript/parse_money_input.ts6,408
vectors.json15,025