This guide covers the internal APIs and utilities of the Aurelia validation system. These are primarily intended for plugin authors, advanced users, and those building custom validation extensions.
Overview
The validation system exposes several utilities and internal APIs that can be useful when building:
Custom validation rules
Custom validation result presenters
Integration plugins
Advanced validation scenarios
Metadata Registry
validationRulesRegistrar
The validationRulesRegistrar is a metadata registry that stores and retrieves validation rules associated with objects and classes.
Purpose: Manages the association between objects/classes and their validation rules using metadata annotations.
API:
constvalidationRulesRegistrar={ // Store validation rules for a targetset(target:IValidateable,rules:IPropertyRule[],tag?:string):void; // Retrieve validation rules for a targetget(target:IValidateable,tag?:string):PropertyRule[] |undefined; // Remove validation rules from a targetunset(target:IValidateable,tag?:string):void; // Check if validation rules are set for a targetisValidationRulesSet(target:IValidateable):boolean; // Default rule set name defaultRuleSetName:'__default';}
Example Usage:
Key Concepts:
Tags: Validation rules can be organized using tags, allowing multiple rule sets for the same object
Default Tag: When no tag is specified, the default tag '__default' is used
Metadata Storage: Rules are stored using Aurelia's metadata system, attached to objects or their constructors
Inheritance: Rules can be retrieved from an object instance or its constructor
Validation Event System
ValidationEvent
The ValidationEvent class describes validation events that are sent to subscribers when validation state changes.
Structure:
Properties:
kind: Type of event - either 'validate' (validation occurred) or 'reset' (validation was cleared)
addedResults: New validation results that were added
removedResults: Previous validation results that were removed
ValidationResultTarget
Links a validation result with the DOM elements it affects.
Structure:
Properties:
result: The validation result (contains valid/invalid state, message, etc.)
targets: Array of DOM elements associated with this validation result
Example: Custom Subscriber:
BindingInfo
Describes a binding that's registered with the validation controller. This class is used internally by the & validate binding behavior.
Structure:
Properties:
sourceObserver: Observer for the binding source that detects changes
target: The HTML element associated with the binding
scope: The binding scope containing the binding context
rules: Optional property rules bound to this binding
propertyInfo: Cached information about the property being validated
Use Case:
This class is primarily used internally, but can be useful when building custom validation triggers or integrating with the validation controller at a low level.
Validation Result Classes
ValidationResult
Represents the result of validating a single rule.
Structure:
Properties:
valid: true if validation passed, false if it failed
message: Error message (only present when valid is false)
propertyName: Name of the property that was validated
object: The object that was validated
rule: The individual rule that was evaluated
propertyRule: The property rule containing this rule
isManual: true if the result was added manually via addError()
id: Auto-generated unique identifier for this result
ControllerValidateResult
The result returned by the validation controller's validate() method.
Structure:
Properties:
valid: true if all validation passed, false if any failed
results: Array of all validation results
instruction: Optional instruction that was passed to validate
Example:
Utility Functions
parsePropertyName
Parses a property name string or accessor function into a property name and expression.
Signature:
Parameters:
property: A property name string (e.g., 'name', 'address.city') or a property accessor function
parser: Expression parser instance
Returns: A tuple containing:
The property name (string or number)
The parsed expression
Example:
Use Cases:
Parsing nested property paths
Converting property accessor functions to expressions
Building custom validation rule implementations
Property Accessor
PropertyAccessor
A type that represents a function for accessing properties. Used in the validation API to allow type-safe property selection.
Type Definition:
Example:
Interfaces for Plugin Authors
IValidationVisitor
Interface for implementing visitors that process validation rules. Used for serialization, transformation, or analysis of rules.
Example: Custom Rule Inspector:
ValidationResultsSubscriber
Interface for receiving validation event notifications.
Example: Analytics Tracker:
Best Practices
When to Use Internals
Use these internal APIs when:
Building Custom Rules: Implementing complex custom validation rules that need deep integration
Creating Plugins: Building validation extensions or integrations
import { validationRulesRegistrar, PropertyRule, Property } from '@aurelia/validation';
export class CustomValidationManager {
public registerRulesForObject(target: any, rules: PropertyRule[]): void {
// Store rules with default tag
validationRulesRegistrar.set(target, rules);
}
public registerRulesWithTag(target: any, rules: PropertyRule[], tag: string): void {
// Store rules with specific tag
validationRulesRegistrar.set(target, rules, tag);
}
public getRules(target: any): PropertyRule[] | undefined {
// Retrieve rules with default tag
return validationRulesRegistrar.get(target);
}
public getTaggedRules(target: any, tag: string): PropertyRule[] | undefined {
// Retrieve rules with specific tag
return validationRulesRegistrar.get(target, tag);
}
public clearRules(target: any): void {
// Remove all rules from target
validationRulesRegistrar.unset(target);
}
public hasRules(target: any): boolean {
// Check if target has any validation rules
return validationRulesRegistrar.isValidationRulesSet(target);
}
}
class ValidationEvent {
public constructor(
public kind: 'validate' | 'reset',
public addedResults: ValidationResultTarget[],
public removedResults: ValidationResultTarget[]
) {}
}
class ValidationResultTarget {
public constructor(
public result: ValidationResult,
public targets: Element[]
) {}
}
import {
ValidationEvent,
ValidationResultTarget,
ValidationResultsSubscriber
} from '@aurelia/validation-html';
export class CustomErrorLogger implements ValidationResultsSubscriber {
public handleValidationEvent(event: ValidationEvent): void {
if (event.kind === 'validate') {
// Log new validation errors
for (const target of event.addedResults) {
if (!target.result.valid) {
console.error(
`Validation error on ${target.result.propertyName}:`,
target.result.message,
'Elements:', target.targets
);
}
}
} else if (event.kind === 'reset') {
// Log cleared errors
console.log(`${event.removedResults.length} validation errors cleared`);
}
}
}
class BindingInfo {
public constructor(
public sourceObserver: IConnectable,
public target: Element,
public scope: Scope,
public rules?: PropertyRule[],
public propertyInfo: PropertyInfo | undefined = void 0
) {}
}
class ValidationResult {
public constructor(
public valid: boolean,
public message: string | undefined,
public propertyName: string | undefined,
public object: any,
public rule: IValidationRule | undefined,
public propertyRule: PropertyRule | undefined,
public isManual: boolean = false
) {}
// Unique identifier for this result
public id: number;
}
class ControllerValidateResult {
public constructor(
public valid: boolean,
public results: ValidationResult[],
public instruction?: Partial<ValidateInstruction>
) {}
}
import { newInstanceForScope, resolve } from '@aurelia/kernel';
import { IValidationController } from '@aurelia/validation-html';
export class FormHandler {
private validationController = resolve(newInstanceForScope(IValidationController));
public async submit(): Promise<void> {
const result = await this.validationController.validate();
// Access overall validation state
if (result.valid) {
console.log('All validation passed!');
}
// Access individual validation results
for (const validationResult of result.results) {
if (!validationResult.valid) {
console.error(
`${validationResult.propertyName}: ${validationResult.message}`
);
}
}
// Check what was validated
if (result.instruction) {
console.log('Validated object:', result.instruction.object);
console.log('Validated property:', result.instruction.propertyName);
}
}
}