When the same rules run in two languages, they drift. A date the browser accepts, the desktop tool rejects. A money amount looks fine in a form, then fails later because JavaScript rounded it. I ran into this while sharing formatters and validators between a desktop app and a standalone page that has no install.
The fix is not a second implementation, and it is not "we will be careful." It is one implementation, compiled twice: Rust on the native side, and the same crate compiled to WebAssembly for the page. This is a short, working walk through that split, using a ledger line as the example, because amounts and dates are where a TypeScript-only check quietly goes wrong.
You will end up with a pure Rust crate, a handful of cargo test cases, a thin WebAssembly wrapper, and a JavaScript call that returns the same violations as the tests.
What we are validating
A ledger line is a debit, a credit, an amount in minor units (cents, or the equivalent), a currency, a booked-on date, and a short reference. The checks are ordinary, which is the point:
- the amount is a whole number, not zero, and not larger than a stated limit
- the currency is a three-letter uppercase code from a list the caller supplies
- the booked-on date is a real calendar day in
YYYY-MM-DDform, and is not after "today" - the reference and account ids match simple character rules, and the two accounts are different
"Today" is not read from a clock inside the crate. The caller passes it in. That is what makes the same function testable, and what makes the native build and the WebAssembly build comparable.
1. Keep the core crate pure
Use a small workspace with two crates: ledger_rules holds every rule and has no knowledge of JavaScript; ledger_rules_wasm is a door that parses JSON and calls the first crate.
The amount is a string, not an i64 or a JavaScript number. Number.MAX_SAFE_INTEGER is 2^53 − 1. Above that, a JSON number is no longer an exact integer. A string such as "2500" or "-199" crosses the boundary without being rounded.
pub struct LedgerLine { pub amount_minor: String, pub currency: String, pub booked_on: String, pub reference: String, pub debit: String, pub credit: String, } pub struct Context<'a> { pub today: &'a str, pub currencies: &'a [&'a str], } pub struct Violation { pub field: &'static str, pub code: &'static str, pub message: String, } pub fn validate(line: &LedgerLine, ctx: &Context<'_>) -> Vec<Violation> { /* ... */ } validate collects every problem and returns them all. It does not panic on bad input, and it does not stop at the first error. A form can highlight several fields at once, and a desktop tool can show the same list.
The amount parser is intentionally strict. It rejects a decimal point, a leading plus, and scientific notation, all of which a JavaScript toString() on a number can produce.
fn parse_amount(raw: &str) -> AmountError { let s = raw.trim(); if s.is_empty() { return AmountError::Empty; } if s.contains('.') || s.contains('e') || s.contains('E') || s.contains('+') { return AmountError::NotInteger; } match s.parse::<i64>() { Ok(0) => AmountError::Zero, Ok(n) if n.unsigned_abs() > AMOUNT_ABS_MAX as u64 => AmountError::OutOfRange, Ok(_) => AmountError::Ok, Err(_) => AmountError::NotInteger, } } Dates need the same attitude. YYYY-MM-DD is compared as a calendar date, including leap years. The crate does not call Date, and it does not accept a timestamp with a time or a zone. If you need those, parse them in the wrapper and pass a calendar day in.
fn parse_iso_date(s: &str) -> Result<(i32, u8, u8), ()> { let bytes = s.as_bytes(); if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' { return Err(()); } let year: i32 = std::str::from_utf8(&bytes[0..4]).unwrap().parse().map_err(|_| ())?; let month: u8 = std::str::from_utf8(&bytes[5..7]).unwrap().parse().map_err(|_| ())?; let day: u8 = std::str::from_utf8(&bytes[8..10]).unwrap().parse().map_err(|_| ())?; if !(1..=12).contains(&month) || day == 0 || day > days_in_month(year, month) { return Err(()); } Ok((year, month, day)) } fn is_leap(year: i32) -> bool { year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) } fn days_in_month(year: i32, month: u8) -> u8 { match month { 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, 4 | 6 | 9 | 11 => 30, 2 if is_leap(year) => 29, 2 => 28, _ => 0, } } The from_utf8(...).unwrap() calls are on fixed slices of an existing &str, so they cannot fail. The date itself is still validated. 2025-02-29 is rejected; 2024-02-29 is accepted; 2026-11-26 is rejected when today is 2026-11-25.
2. Test the rules natively first
Do not start with the browser. If a rule is wrong, you want cargo test to say so in a fraction of a second, on the same crate the desktop app will link.
#[test] fn rejects_a_javascript_style_decimal_amount() { let mut line = valid(); line.amount_minor = "25.00".into(); assert_eq!(codes(&line), vec![("amount_minor", "not_integer")]); } #[test] fn rejects_impossible_and_future_dates() { let mut line = valid(); line.booked_on = "2025-02-29".into(); assert_eq!(codes(&line), vec![("booked_on", "format")]); line.booked_on = "2024-02-29".into(); assert!(codes(&line).is_empty()); line.booked_on = "2026-11-26".into(); assert_eq!(codes(&line), vec![("booked_on", "in_future")]); } valid() is a well-formed line, and codes maps each violation to (field, code) so the tests stay short. Add cases for an empty amount, a zero amount, a lowercase currency, a missing account, and two accounts that match. I also keep one test that feeds several problems at once, so a later change cannot silently start returning only the first error.
3. Add a thin WebAssembly door
The second crate depends on ledger_rules, serde_json, and wasm-bindgen. Pin wasm-bindgen to the same version as the wasm-bindgen command you will run. The crate's only job is to turn two JSON strings into a LedgerLine and a Context, call validate, and turn the result back into JSON. LineJson and ContextJson are Serde types with the same fields. If the JSON itself is invalid, the function still returns a JSON array, with field set to _, and it does not panic.
#[wasm_bindgen] pub fn validate_ledger_line(line_json: &str, ctx_json: &str) -> String { let line: LineJson = match serde_json::from_str(line_json) { Ok(v) => v, Err(err) => return error("_", "bad_json", &format!("Invalid line JSON: {err}")), }; let ctx: ContextJson = match serde_json::from_str(ctx_json) { Ok(v) => v, Err(err) => return error("_", "bad_json", &format!("Invalid context JSON: {err}")), }; let currencies: Vec<&str> = ctx.currencies.iter().map(String::as_str).collect(); let context = Context { today: &ctx.today, currencies: ¤cies, }; let line = LedgerLine { amount_minor: line.amount_minor, currency: line.currency, booked_on: line.booked_on, reference: line.reference, debit: line.debit, credit: line.credit, }; let violations: Vec<serde_json::Value> = ledger_rules::validate(&line, &context) .into_iter() .map(|v| { serde_json::json!({ "field": v.field, "code": v.code, "message": v.message, }) }) .collect(); serde_json::to_string(&violations) .unwrap_or_else(|_| error("_", "encode", "Could not encode the result.")) } Build it, then generate the JavaScript glue. --target nodejs is convenient for a check script; use --target web when the caller is a page.
rustup target add wasm32-unknown-unknown cargo test -p ledger_rules cargo build --target wasm32-unknown-unknown --release -p ledger_rules_wasm wasm-bindgen target/wasm32-unknown-unknown/release/ledger_rules_wasm.wasm \ --out-dir js/pkg --target nodejs --out-name ledger_rules From JavaScript, or TypeScript, the door is one function that takes two JSON strings and returns a JSON array:
import { validate_ledger_line } from "./pkg/ledger_rules.js"; type Violation = { field: string; code: string; message: string }; const ctx = { today: "2026-11-25", currencies: ["EUR", "USD", "GBP", "IRR"], }; const line = { amount_minor: "2500", currency: "EUR", booked_on: "2026-11-20", reference: "INV-1092", debit: "CASH1001", credit: "REV2002", }; const violations: Violation[] = JSON.parse( validate_ledger_line(JSON.stringify(line), JSON.stringify(ctx)), ); For a well-formed line, violations is empty. Change amount_minor to "25.00" and you get { field: "amount_minor", code: "not_integer" }, which is the same pair the Rust test asserts.
I compiled this crate, ran eight native tests with cargo test, generated the Node module with wasm-bindgen 0.2.130, and ran the same cases from Node. They agreed.
Pitfalls
Pass amounts as strings. If the page holds the amount in a number and then JSON.stringifys the object, values above Number.MAX_SAFE_INTEGER will already have been rounded before Rust sees them. Keep the value as text from the input field to the crate.
Do not panic in the wrapper. A panic in WebAssembly is a poor debugging experience and a blank form. Parse errors should come back as data, in the same shape as rule violations.
Do not read a clock, the filesystem, or the network in the shared crate. The moment a rule calls the current time, the tests need stubs and the two runtimes can disagree. Pass "today", currency lists, and limits in as Context.
Keep the wrapper thin. If a new rule lands only in the TypeScript that calls the module, you are back to two implementations. New rules go in ledger_rules first, with a test, and the wrapper only learns a new field if the JSON shape changes.
Pin the tools together. The wasm-bindgen crate and the wasm-bindgen CLI must be the same version. A mismatch often fails at generate time with a version error, which is easy to misread as a target problem.
Be precise about dates. A JavaScript Date will accept values this crate rejects, and it will also surprise you with time zones. If the user typed a calendar day, validate that day.
When this is worth it
For a required-field check on a marketing form, a second implementation is cheaper than a toolchain. This split starts to pay when the rules have a shape you do not want to write twice: calendar dates, integer money, checksums, formatters, or OpenAPI-style constraints that also need to run in a desktop app.
I use it in Alita when a desktop window and a standalone page have to agree. The core stays a normal Rust library. WebAssembly is only the way a browser is allowed to call it.
I'm Aran Shayan, a frontend developer at SOHA who builds data-heavy interfaces and the APIs behind them. More at aranshayan.com.
