Form Validate With Composable Rules
Validate form fields with composable rule functions that return typed errors and support async dependency checks.
Code
export function composeRules(rules){return async function(value,context){for(const rule of rules){const result=await rule(value,context);if(result!==true)return result;}return true;};}export const required=(msg='required')=>v=>v!==null&&v!==undefined&&String(v).trim()!==''?true:msg;export const minLen=(n,msg)=>v=>String(v).length>=n?true:(msg??'min length '+n);export const matches=(regex,msg)=>v=>regex.test(String(v))?true:(msg??'invalid format');export const asyncUnique=(check,msg)=>async v=>await check(v)?true:(msg??'already taken');How it works
The working surface is the functions required, minLen, matches and asyncUnique — everything else is wiring.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
What to watch for
- The guard
result!==trueshort-circuits the flow with an earlyreturnwhen its condition holds.
Putting it to use
The primary signature is export function composeRules(rules)
composeRules is what another module would consume; nothing else here is load-bearing for callers.
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. The file defines `required`, `minLen`, `matches` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.