Form Validate With Composable Rules

Validate form fields with composable rule functions that return typed errors and support async dependency checks.

JavascriptForm Validation

Code

javascriptsnippet
1 line
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!==true short-circuits the flow with an early return when 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

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.