Currency Code Validation: How to Check ISO 4217 Codes in Your App

6 min read

Currency Code Validation: How to Check ISO 4217 Codes in Your App

Currency code validation looks like a one-line regex problem until real input arrives. Users type "usd", "US$", "RMB" or " EUR ". A CSV import contains "XXX". A crypto ticker ends up in a field meant for ISO 4217 codes. Each of these can break a conversion or, worse, silently produce a wrong number.

The short answer: validate in three layers. First normalize and check the format. Second, check the code against a list of codes you actually support. Third, handle the "this pair can't be priced" error from the rate source instead of assuming that a well-formed code always works. This article walks through each layer and shows where an exchange-rate API fits.

What a valid currency code looks like

ISO 4217 defines three-letter alphabetic codes for currencies, plus three-digit numeric codes. For most fiat currencies the first two letters are the country code and the third is an initial of the currency name: USD, EUR, GBP, JPY, CHF. That pattern is a convention, not a rule you can validate against.

A few things trip people up:

  • Symbols are not codes. "$" can mean USD, CAD, AUD, MXN and many others. Never store a symbol as the identifier.
  • Informal names are not codes. "RMB" is a common name for the Chinese currency; the code is CNY. "CNH" is a market convention for offshore yuan, not an ISO code.
  • Codes change. Currencies get replaced and renamed. Croatia moved from HRK to EUR in 2023, for example. A hard-coded list from five years ago will have gaps.
  • Special codes exist. XAU (gold) and XAG (silver) are in the ISO 4217 "X" range. XXX means "no currency" and XTS is reserved for testing. Treat those as deliberate cases, not typos.
  • Crypto tickers are outside ISO. Tickers such as BTC or ETH have no governing standard, vary in length, may contain digits, and can be reused by different projects.

So a format check can only reject obvious garbage. It cannot tell you that a code is supported.

Layer 1: normalize, then check the format

Do this at the edge, where input enters your system: forms, query strings, import files, webhook payloads from other systems.

const CODE_PATTERN = /^[A-Z0-9]{2,10}$/;

export function normalizeCode(input) {
  const code = String(input ?? "").trim().toUpperCase();
  return CODE_PATTERN.test(code) ? code : null;
}

normalizeCode(" usd ");  // "USD"
normalizeCode("US$");    // null
normalizeCode("");       // null

The pattern is deliberately lenient: it accepts three-letter fiat codes and longer crypto tickers. If a field must be fiat only, tighten it to ^[A-Z]{3}$ for that field.

Normalizing before validating matters because you want one canonical form everywhere: in your database, in cache keys and in API calls. "usd" and "USD" should never be two different cache entries.

One trap in JavaScript: Intl.NumberFormat and Intl.DisplayNames accept any well-formed three-letter string and only throw a RangeError for malformed ones. They are formatting tools, not validators. new Intl.NumberFormat("en", { style: "currency", currency: "ZZZ" }) does not fail just because ZZZ is not a real currency.

Layer 2: check against the list you support

Format-valid does not mean supported. A pricing page that lets a visitor pick any of 300 codes is worse than one that offers the 25 you can actually settle and display.

Keep an explicit allow-list and build it from a source of truth rather than a copy-pasted array. GetRatesAPI exposes the catalog through free endpoints: GET /v1/assets, /v1/assets/fiat and /v1/assets/crypto list the supported codes and are not billed. The same list is on the currencies page, and the assets documentation describes the response.

A practical pattern:

  1. Fetch the catalog on startup or on a schedule, for example once a day. It changes rarely.
  2. Keep it in memory (or in your cache) as a set of normalized codes.
  3. Intersect it with your own business rules: the currencies you display, settle or invoice in.
  4. Use that final list to populate dropdowns and to validate API input.

For a dropdown, show a human-readable label but submit the code. In the browser you can generate names without maintaining a translation table:

const names = new Intl.DisplayNames(["en"], { type: "currency" });

function optionLabel(code) {
  return `${code} - ${names.of(code)}`; // "EUR - Euro"
}

For crypto assets or metals, Intl.DisplayNames may not have a name. Fall back to the code itself, or to a name from your own data. That is fine; the code is the identifier.

Layer 3: let the API tell you when a pair fails

Even with a clean allow-list, you should treat the rate lookup itself as a validator. Lists get stale, code paths skip the dropdown (API clients, imports, AI agents), and a request can be wrong in ways a list does not capture.

GetRatesAPI separates the failure types, and you should match on the code field only, never on the message text:

Error codeHTTPMeaningWhat to do
invalid_asset_symbol400A code is malformed or not a known assetShow a field-level error; do not retry
invalid_amount400The amount can't be parsedShow an amount error; do not retry
unsupported_pair404The pair can't be pricedOffer another currency; do not retry

Malformed requests are not billed, so a stray bad code does not eat into your monthly quota. For the full list of codes and retry guidance, see exchange rate API error handling and the errors reference.

Here is a small wrapper that combines layers 1 and 3 and returns a result your UI can act on:

export async function getRate(base, quote) {
  const b = normalizeCode(base);
  const q = normalizeCode(quote);
  if (!b || !q) return { ok: false, reason: "bad_format" };

  const res = await fetch(`https://api.getratesapi.com/v1/rates/${b}/${q}`, {
    headers: { Authorization: `ApiKey ${process.env.GETRATES_API_KEY}` },
  });
  const body = await res.json();

  if (res.ok) {
    // body.rate is a string: keep it a string until you use a decimal type
    return { ok: true, rate: body.rate, status: body.status, asOf: body.as_of };
  }

  switch (body.code) {
    case "invalid_asset_symbol":
      return { ok: false, reason: "unknown_code" };
    case "unsupported_pair":
      return { ok: false, reason: "pair_unavailable" };
    default:
      return { ok: false, reason: "try_later", requestId: body.request_id };
  }
}

Log the request_id for anything you cannot explain; it is the fastest way to trace a specific failure.

Batch lookups: partial failure is normal

When you request several quotes against one base, a single unsupported code should not sink the whole call. With GET /v1/rates/{base}?quote=EUR,GBP,JPY (up to 20 quotes, still one request unit), unsupported quotes are listed in an unsupported field instead of failing the request. Your code should read that list and report those codes to the user or to your logs.

import os
import requests

def fetch_quotes(base, quotes):
    resp = requests.get(
        f"https://api.getratesapi.com/v1/rates/{base}",
        params={"quote": ",".join(quotes)},
        headers={"Authorization": f"ApiKey {os.environ['GETRATES_API_KEY']}"},
        timeout=10,
    )
    data = resp.json()
    if not resp.ok:
        raise RuntimeError(f"{data['code']} (request {data['request_id']})")

    missing = data.get("unsupported", [])
    if missing:
        print(f"Skipped unsupported codes: {', '.join(missing)}")
    return data

More on batching in get multiple exchange rates in one API call.

Validation mistakes worth avoiding

  • Validating only on the client. Browser checks are a convenience. The server must repeat them.
  • Rejecting by message text. Error messages can change; error codes are the contract.
  • Retrying a 400 or 404. A bad code stays bad. Retries only help for temporarily_unavailable and rate limits, as covered in the rate limit guide.
  • Storing the user's raw input. Store the normalized code. Keep the original only if you need an audit trail.
  • Using a fiat-only regex for every field. Crypto and metals will be rejected for no good reason.
  • Falling back to a rate of 1. When a pair fails, show an error. A silent default turns a validation problem into a pricing bug.

Putting it together

A solid flow is short: normalize the input, check it against your supported set, call the API, and map invalid_asset_symbol and unsupported_pair to clear messages. Each layer catches a different class of problem, and none of them is expensive.

If you want to try it, create a free account, fetch the catalog, and use the dashboard playground to see what happens with a bad code. Plan details are on the pricing page, and the REST documentation covers every endpoint used above.

All articles →
Currency Code Validation: ISO 4217 Checks That Work — GetRatesAPI