UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

37 lines (36 loc) 1.32 kB
import { CURRENCY_CODES } from "../util/currency.js"; import { NULLABLE } from "./NullableSchema.js"; import { StringSchema } from "./StringSchema.js"; /** * Type of `StringSchema` that defines a valid currency code. */ export class CurrencyCodeSchema extends StringSchema { currencies; constructor({ one = "currency", title = "Currency", currencies = CURRENCY_CODES, ...options }) { super({ one, title, ...options, min: 3, max: 3, // Valid currency code is 3 uppercase letters. rows: 1, case: "upper", match: /^[A-Z]{3}$/, // Valid currency code is 3 uppercase letters. }); this.currencies = currencies; } sanitize(insaneString) { // Strip characters that aren't A-Z (including whitespace). return super.sanitize(insaneString).replace(/[^A-Z+]/g, ""); } validate(value) { const currency = super.validate(value); if (!this.currencies.includes(currency)) throw "Unknown currency code"; return currency; } } /** Valid currency code, e.g. `GBP` */ export const CURRENCY_CODE = new CurrencyCodeSchema({}); /** Valid currency code, e.g. `GBP`, or `null` */ export const NULLABLE_CURRENCY_CODE = NULLABLE(CURRENCY_CODE);