Skip to content

Validator

Defined in: validator.ts:76, validator.ts:583

Validator for handling synchronous and asynchronous validations

  • Supports both sync and async validation handlers
  • Tracks validation state (isValidating)
  • Looks up errors by key path pattern
  • Supports nested validators

AsyncHandler<T, Expr> = (expr: Expr, builder: ValidationErrorMapBuilder<T>, abortSignal: AbortSignal) => Promise<void>

Defined in: validator.ts:591

Async handler

Expr

The expression observed

ValidationErrorMapBuilder<T>

The builder to build the errors

AbortSignal

The abort signal

Promise<void>


HandlerOptions<Expr> = object

Defined in: validator.ts:609

Handler options

Expr = unknown

optional delayMs?: number

Defined in: validator.ts:621

Throttle reaction. [milliseconds]

100

optional equals?: IEqualsComparer<Expr>

Defined in: validator.ts:627

The equality comparer for the expression.

Only effective for async handlers.

optional initialRun?: boolean

Defined in: validator.ts:615

Whether to run the handler immediately

true

InstantHandler<T> = (builder: ValidationErrorMapBuilder<T>) => void

Defined in: validator.ts:607

Instant handler

ValidationErrorMapBuilder<T>

The builder to build the errors

void


SyncHandler<T> = (builder: ValidationErrorMapBuilder<T>) => void

Defined in: validator.ts:601

Sync handler

ValidationErrorMapBuilder<T>

The builder to build the errors

void

static defaultDelayMs: number = 100

Defined in: validator.ts:77


static get<T>(target): Validator<T>

Defined in: validator.ts:98

Get a validator instance for the target object.

T extends object

T

Validator<T>

  • Returns existing instance if one exists for the target
  • Creates new instance if none exists
  • Instances are cached by the identity of the target, so an object inheriting from a validated one gets its own
  • Nothing is written to the target, so frozen, sealed and non-extensible objects are supported
  • Instances are garbage collected with the target only if everything their handlers observe is too

TypeError if the target is not an object.


static getSafe<T>(target): Validator<T> | null

Defined in: validator.ts:109

Get a validator instance for the target object.

Same as Validator.get but returns null instead of throwing an error.

T

Validator<T> | null

readonly id: string

Defined in: validator.ts:79


get asyncState(): number

Defined in: validator.ts:283

The number of pending/running async jobs.

number

@computed


get firstErrorMessage(): string | null

Defined in: validator.ts:188

Get the first error message (including nested objects)

string | null

@computed


get invalidKeyCount(): number

Defined in: validator.ts:139

The number of invalid keys

number

@computed


get invalidKeyPathCount(): number

Defined in: validator.ts:161

The number of invalid key paths

number

@computed


get invalidKeyPaths(): ReadonlySet<KeyPath>

Defined in: validator.ts:171

The key paths that have errors

Keys of nested objects are included.

ReadonlySet<KeyPath>

@computed


get invalidKeys(): ReadonlySet<KeyPath>

Defined in: validator.ts:149

The keys that have errors

Keys of nested objects are NOT included.

ReadonlySet<KeyPath>

@computed


get isValid(): boolean

Defined in: validator.ts:133

Whether no errors are found

boolean

@computed


get isValidating(): boolean

Defined in: validator.ts:295

Whether the validator is computing errors (including nested validators)

boolean

@computed


get nested(): Generator<StandardNestedFetcher.Entry<Validator<any>>, void, unknown>

Defined in: validator.ts:359

Nested validators

A fresh iterator over the @nested entries, in annotation order and then in collection order. Each entry carries the name of the annotated member in key ("items"), the address of the nested object in keyPath ("items.0") and its validator in data.
Each read starts a new iteration, and an iterator is consumed once, so a second pass needs a second read.
There is no lookup by name: entries are not unique by key path. To reach the validator of one nested object, go through the property — Validator.get(target.child) is cached per subject, so it is the very instance yielded here — or iterate and match entry.key, which is KeyPath.Self for a @nested.hoist member rather than the name it is declared with. Errors are looked up by pattern with findErrors, which searches nested validators itself.

Generator<StandardNestedFetcher.Entry<Validator<any>>, void, unknown>


get reactionState(): number

Defined in: validator.ts:275

The number of pending/running reactions.

number

@computed


addAsyncHandler<Expr>(expr, handler, opt?): () => void

Defined in: validator.ts:455

@action

Add an async handler

() => Expr

The expression to observe

Validator.AsyncHandler<T, NoInfer<Expr>>

The async handler to call when the expression changes

Validator.HandlerOptions<NoInfer<Expr>>

The handler options

A function to remove the handler

() => void

  • Handler runs immediately when added for initial validation
  • Handler is called when the watched expression changes
  • Changes are throttled by default delay
  • Changes made while the handler is running are queued, not aborted: the latest value is validated after the running handler settles
  • Provides abort signal, which is aborted when the validator is reset or the handler is removed; the result of an aborted run is discarded, so the errors it collected are not applied

addSyncHandler(handler, opt?): () => void

Defined in: validator.ts:416

Add a sync handler

Validator.SyncHandler<T>

The sync handler containing observable expressions

Validator.HandlerOptions<unknown>

A function to remove the handler

() => void

  • Handler runs immediately when added for initial validation
  • Handler is called when observable expressions within it change
  • Changes are throttled by default delay

findErrors(...patterns): Generator<[keyPath: KeyPath, error: ValidationError], void, any>

Defined in: validator.ts:221

Find the errors of the key paths matching any of the patterns

  • Yields each error once, with its key path relative to this validator, however many patterns match it
  • Searches nested validators, including hoisted ones, for the rest of the patterns
  • Reads only the @nested members the patterns can reach, which is all of them when one starts with a wildcard

...KeyPathPattern[]

Generator<[keyPath: KeyPath, error: ValidationError], void, any>

KeyPathPattern for the syntax


getErrorMessages(...patterns): Set<string>

Defined in: validator.ts:196

Get the error messages of the key paths matching any of the patterns

...KeyPathPattern[]

Set<string>


hasErrors(...patterns): boolean

Defined in: validator.ts:205

Check if any key path matching any of the patterns has errors

...KeyPathPattern[]

boolean


reset(): void

Defined in: validator.ts:371

@action

Reset the validator

Use with caution.
Since validation is reactive, errors won't reappear until you make some changes.
Running async validations are aborted, and their results are discarded.

void


updateErrors(key, handler): () => void

Defined in: validator.ts:390

@action

Update the errors immediately

symbol

Validator.InstantHandler<T>

A function to remove the errors

() => void


waitForValidation(opt?): Promise<void>

Defined in: validator.ts:326

Wait for the validation to complete

A shorthand for:

await when(() => !validator.isValidating);

AbortSignal

Abort signal to stop waiting

Promise<void>

A promise that resolves once isValidating is false, or rejects with the reason of the signal if it is aborted first

  • Resolves right away if nothing is being validated
  • Waits for nested validators as well, as isValidating includes them
  • Deadlocks when awaited in an async handler of this validator or of a nested one: the handler is part of the validation it waits for