TypeScript decorator-based validation library
Interfaces
- Comparable
Defines the equality comparison API for model objects
- DateValidatorOptions
Defines options for date validation
- DecorationBuilderBuild
Represents the build stage of the decoration builder, providing the ability to apply the configured decorator to a target. This is the final stage in the builder chain.
- DecorationBuilderEnd
Represents the extension stage of the decoration builder, providing the ability to add additional decorators to the existing configuration.
- DecorationBuilderMid
Represents the middle stage of the decoration builder, extending the end stage and providing the ability to define the primary decorators for the configuration.
- DecorationBuilderStart
Represents the initial stage of the decoration builder, providing the entry point for the builder pattern by specifying the key for the decorator.
- Hashable
Defines the hashing API for model objects
- IDecorationBuilder
A unified interface that combines all stages of the decoration builder pattern, providing a complete API for creating, configuring, and applying decorators. This interface is implemented by the Decoration class.
- IValidatorRegistry
Defines the contract for a registry that stores and retrieves validators. The registry is responsible for maintaining a collection of validators and providing access to them by key.
- ListValidatorOptions
Defines options for list validation
- MaxLengthValidatorOptions
Defines options for maximum length validation
- MaxValidatorOptions
Defines options for maximum value validation
- MinLengthValidatorOptions
Defines options for minimum length validation
- MinValidatorOptions
Defines options for minimum value validation
- PatternValidatorOptions
Defines options for pattern validation using regular expressions
- Serializable
Defines the serialization API for model objects
- Serializer
Defines the contract for classes that can convert model objects to and from string representations. Serializers are used to persist models or transmit them over networks.
- StepValidatorOptions
Defines options for step validation, specifying the step increment
- TypeValidatorOptions
Defines options for type validation, specifying allowed types
- UniqueValidatorOptions
Defines options for unique validation
- Validatable
Defines the Validation API for validation behavior on models, supporting both synchronous and asynchronous validations. Implementers must provide a
hasErrors
method that performs the validation and returns either validation errors or undefined if validation passes.
Members
# static constant Primitives
References the relevant JS primitives
Properties:
Name | Type | Description |
---|---|---|
STRING |
string
|
references the string primitive |
NUMBER |
string
|
references the number primitive |
BOOLEAN |
string
|
references the boolean primitive |
BIGINT |
string
|
references the bigint primitive |
# static constant ReservedModels
References the Reserved model names to ignore during Model rebuilding
Properties:
Name | Type | Description |
---|---|---|
STRING |
string
|
|
OBJECT |
string
|
|
NUMBER |
string
|
|
BOOLEAN |
string
|
|
BIGINT |
string
|
|
DATE |
string
|
# static constant VALIDATION_PARENT_KEY
Symbol used to internally track the parent object during nested validation
Symbol key for tracking parent-child relationships in validation
# static constant VERSION
Stores the semantic version number of the package
Current version of the reflection package
string
# static constant exports.DefaultFlavour
Defines the default flavour used by the Decoration class when no specific flavour is provided. This constant is used throughout the library as the fallback flavour for decorators.
Default flavour identifier for the decorator system
string
# static readonly exports.ModelKeys
Defines the various Model keys used for reflection and metadata storage. These keys are used throughout the library to store and retrieve metadata about models, their properties, and their behavior.
Enum containing metadata keys used for reflection in the model system
Properties:
Name | Type | Description |
---|---|---|
REFLECT |
string
|
Prefix to all other keys, used as a namespace |
TYPE |
string
|
Key for storing design type information |
PARAMS |
string
|
Key for storing method parameter types |
RETURN |
string
|
Key for storing method return type |
MODEL |
string
|
Key for identifying model metadata |
ANCHOR |
string
|
Anchor key that serves as a ghost property in the model |
CONSTRUCTION |
string
|
Key for storing construction information |
ATTRIBUTE |
string
|
Key for storing attribute metadata |
HASHING |
string
|
Key for storing hashing configuration |
SERIALIZATION |
string
|
Key for storing serialization configuration |
RegExp
# static constant exports.regexpParser
This regular expression is used to parse string patterns in the format "/pattern/flags". It captures the pattern and flags separately, allowing the creation of a RegExp object with the appropriate flags.
Regular expression for parsing string patterns with flags
# static constant jsTypes
References the basic supported js types
Properties:
Name | Type | Description |
---|---|---|
string |
string
|
|
array |
string
|
|
number |
string
|
|
boolean |
string
|
|
symbol |
string
|
|
function |
string
|
|
object |
string
|
|
undefined |
string
|
|
null |
string
|
|
BIGINT |
string
|
Methods
# static MinLengthValidator#hasErrors(value, options) → {string|undefined}
Parameters:
Name | Type | Description |
---|---|---|
value |
string
|
Array
|
|
options |
MinLengthValidatorOptions
|
string
|
undefined
# static bindDateToString(dateopt, formatopt) → {Date|undefined}
Modifies a Date object to return a formatted string when toString or toISOString is called. This function overrides the default toString and toISOString methods of the Date object to return the date formatted according to the specified format string.
Binds a specific date format to a Date object's toString and toISOString methods
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
date |
Date
|
<optional> |
The Date object to modify |
format |
string
|
<optional> |
The format string to use for formatting the date |
The modified Date object or undefined if no date was provided
Date
|
undefined
# static construct(constructor, argsopt) → {M}
Helper Function to override constructors
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
constructor |
function
|
||
args |
Array.<any>
|
<optional> |
the new instance
M
# static dateFromFormat(date, format) → {Date}
Reverses the process from formatDate
Parameters:
Name | Type | Description |
---|---|---|
date |
string
|
the date string to be converted back into date |
format |
string
|
the date format |
the date from the format or the standard new Date({@prop date}) if the string couldn't be parsed (are you sure the format matches the string?)
Date
# static exports.bulkModelRegister(modelsopt)
Bulk Registers Models
Useful when using bundlers that might not evaluate all the code at once
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
models |
Array.<Constructor.<M>>
|
Array.<{name: string, constructor: Constructor.<M>}>
|
<optional> |
# static exports.isGreaterThan(a, b) → {boolean}
Checks if a
is greater than b
.
Checks if a
is greater than b
.
Supports comparison for numbers and Date objects.
Parameters:
Name | Type | Description |
---|---|---|
a |
any
|
The value to validate. |
b |
any
|
The value to compare against. |
If either a
or b
is null
or undefined
.
Error
If values are of mismatched or unsupported types.
TypeError
True if a
is greater than b
, otherwise false.
boolean
# static exports.isLessThan(a, b) → {boolean}
Compares two values to determine if the first is less than the second.
Supports numbers and dates. Throws an error for unsupported types.
Parameters:
Name | Type | Description |
---|---|---|
a |
any
|
The first value to compare. |
b |
any
|
The second value to compare against. |
If either a
or b
is null
or undefined
.
Error
If values are of mismatched or unsupported types.
TypeError
True if a
is less than b
, false otherwise.
boolean
# static exports.isValidForGteOrLteComparison(a, b) → {boolean}
Validates whether two values are eligible for comparison using >= or <= operators.
Validates whether two values are eligible for comparison using >= or <= operators.
Supported types: undefined
, number
, bigint
, and Date
.
Parameters:
Name | Type | Description |
---|---|---|
a |
The first value to compare. |
|
b |
The second value to compare. |
If either value is of an unsupported type.
TypeError
True if both values are of supported types.
boolean
# static exports.parseDate(format, vopt)
Parses a date from a specified format
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
format |
string
|
||
v |
string
|
Date
|
number
|
<optional> |
# static findLastProtoBeforeObject(obj)
Recursively finds the last prototype before Object
Parameters:
Name | Type | Description |
---|---|---|
obj |
object
|
# static formatDate(date, patternStropt) → {string}
Date Format Handling
Code from https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date
Using similar formatting as Moment.js, Class DateTimeFormatter (Java), and Class SimpleDateFormat (Java), I implemented a comprehensive solution formatDate(date, patternStr) where the code is easy to read and modify. You can display date, time, AM/PM, etc. Date and Time Patterns yy = 2-digit year; yyyy = full year M = digit month; MM = 2-digit month; MMM = short month name; MMMM = full month name EEEE = full weekday name; EEE = short weekday name d = digit day; dd = 2-digit day h = hours am/pm; hh = 2-digit hours am/pm; H = hours; HH = 2-digit hours m = minutes; mm = 2-digit minutes; aaa = AM/PM s = seconds; ss = 2-digit seconds S = miliseconds
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
date |
Date
|
||
patternStr |
string
|
<optional> |
defaults to 'yyyy/MM/dd' |
the formatted date
string
# static hashCode(obj) → {number}
Mimics Java's String's Hash implementation
Parameters:
Name | Type | Description |
---|---|---|
obj |
string
|
number
|
symbol
|
Date
|
hash value of obj
number
# static hashObj(obj) → {string}
Hashes an object by combining the hash of all its properties
Parameters:
Name | Type | Description |
---|---|---|
obj |
Record.<string, any>
|
the resulting hash
string
# static isValidDate(date) → {boolean}
A utility function that determines if a value is a valid Date object. This function is more reliable than using instanceof Date as it also checks that the date is not NaN, which can happen with invalid date strings.
Safely checks if a value is a valid Date object
Parameters:
Name | Type | Description |
---|---|---|
date |
any
|
The value to check |
True if the value is a valid Date object, false otherwise
boolean
# static sf(string, args) → {string}
Util function to provide string format functionality similar to C#'s string.format
alias for stringFormat
Parameters:
Name | Type | Description |
---|---|---|
string |
string
|
|
args |
string
|
replacements made by order of appearance (replacement0 wil replace {0} and so on) |
formatted string
string
# static stringFormat(string, argsopt) → {string}
Util function to provide string format functionality similar to C#'s string.format
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
string |
string
|
||
args |
Array.<(string|number)>
|
<optional> |
replacements made by order of appearance (replacement0 wil replace {0} and so on) |
formatted string
string
# static twoDigitPad(num) → {string}
Util function to pad numbers
Parameters:
Name | Type | Description |
---|---|---|
num |
number
|
string
# static validate(model, asyncopt, …propsToIgnore) → {ConditionalAsync.<Async, (ModelErrorDefinition|undefined)>}
This function inspects a given model object, identifies decorated properties that require validation,
and applies the corresponding validation rules. It also supports nested model validation and gracefully
merges any validation errors. For collections (Array/Set), it enforces the presence of the @list
decorator
and checks the type of elements. If a property is a nested model, it will call hasErrors
on it and flatten
the nested error keys using dot notation.
Validates the properties of a Model
instance using registered decorators.
Supports both synchronous and asynchronous validation flows, depending on the async
flag.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
model |
M
|
The model instance to be validated. Must extend from |
|
async |
Async
|
<optional> |
A flag indicating whether validation should be asynchronous. |
propsToIgnore |
string
|
<repeatable> |
A variadic list of property names that should be skipped during validation. |
- See:
Returns either a ModelErrorDefinition
containing validation errors,
or undefined
if no errors are found. When async
is true
, returns a Promise.
ConditionalAsync.<Async, (ModelErrorDefinition|undefined)>
Type Definitions
object
# Constructor
Definition of a Class Constructor that can create instances of a specified type
Generic type for class constructor functions
Properties:
Name | Type | Description |
---|---|---|
...args: |
T
|
any[] |
# FlavourResolver(target, target) → {string}
Defines a function type that determines the appropriate flavour for a given target object. This is used by the Decoration class to resolve which flavour of decorator to apply based on the target.
Type definition for a function that resolves the flavour for a target
Parameters:
Name | Type | Description |
---|---|---|
target |
object
|
The target object to resolve the flavour for |
target |
object
|
The resolved flavour identifier
string
# HashingFunction(value, args)
Defines teh type for a Hashing function
Parameters:
Name | Type | Description |
---|---|---|
value |
any
|
|
args |
Array
|
# InstanceCallback(instance, args)
defines the tpe os an InstanceCallback function
Parameters:
Name | Type | Description |
---|---|---|
instance |
any
|
|
args |
Array
|
T
|
Partial.<T>
|
Record.<string, any>
# ModelArg
Definition of a Model Constructor Argument that can be a complete model, partial model, or plain object
Type representing valid argument types for model constructors
- See:
-
- ModelConstructor
# ModelBuilderFunction(self, objopt, self, objopt) → {T}
Type definition for a model builder function that populates model properties
Function type for building model instances from objects
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
self |
T
|
The target model instance to populate |
|
obj |
T
|
Record.<string, any>
|
<optional> |
The source object containing properties to copy |
self |
T
|
||
obj |
T
|
Record.<string, any>
|
<optional> |
- The populated model instance
T
object
# ModelConstructor
Definition of a Model Constructor that creates instances of Model subclasses
Specialized constructor type for Model classes
Properties:
Name | Type | Description |
---|---|---|
model?: |
T
|
ModelArg |
Object
# ValidationDecoratorDefinition
Extends the base DecoratorMetadata type with validation-specific properties. This type represents the metadata for a single validation decorator applied to a property.
Type definition for individual validation decorator metadata
Properties:
Name | Type | Attributes | Description |
---|---|---|---|
props |
ValidationElementDefinition
|
The validation element properties and configuration |
|
props |
ValidationElementDefinition
|
||
async |
boolean
|
<optional> |
object
# ValidationElementDefinition
Type for a validator element metadata
Properties:
Name | Type | Attributes | Description |
---|---|---|---|
indexer: |
any
|
string |
|
value |
string
|
number
|
<optional> |
|
message |
string
|
||
description |
string
|
||
types |
Array
|
<optional> |
Object
# ValidationMetadata
Defines the structure of metadata attached to properties by validation decorators. This metadata is used during validation to determine validation rules and error messages.
Type definition for metadata used by validation decorators
Properties:
Name | Type | Attributes | Description |
---|---|---|---|
args |
Array.<any>
|
<optional> |
Optional arguments for the validator |
message |
string
|
Error message to display when validation fails |
|
types |
Array.<string>
|
<optional> |
Array of type names that the property can have |
async |
boolean
|
Indicates whether the validator associated with the decorator performs asynchronous validation logic.
Use |
|
indexer: |
any
|
string |
|
args |
Array
|
<optional> |
|
message |
string
|
||
types |
Array
|
<optional> |
|
async |
boolean
|
Object
# ValidationPropertyDecoratorDefinition
Defines the structure that associates a property with its validation decorators. This type is used to track which decorators are applied to a specific property during validation.
Type definition for property-level validation decorator configuration
Properties:
Name | Type | Attributes | Description |
---|---|---|---|
prop |
string
|
symbol
|
The property name or symbol that the decorators are applied to |
|
decorators |
Array.<ValidationDecoratorDefinition>
|
Array of decorator definitions applied to the property |
|
prop |
string
|
symbol
|
||
decorators |
Array
|
||
async |
boolean
|
<optional> |