StaticcreateCreates a string-based Value Object with validation.
Runs all validators in sequence and creates the Value Object if all pass. Validators receive the raw value and should return Results.
The raw string value
The Value Object class constructor
Array of validation functions
Result with the created Value Object or validation error
class Email extends ValueObject {
private constructor(readonly value: string) { super(); }
static create(value: string): Result<Email, DomainError> {
return ValueObjectFactory.createString(value, Email, [
(v) => Validators.notEmpty(v, 'Email'),
(v) => Validators.email(v)
]);
}
protected getEqualityComponents() { return [this.value]; }
}
StaticcreateCreates a number-based Value Object with validation.
Runs all validators in sequence and creates the Value Object if all pass. Validators receive the raw number and should return Results.
The raw number value
The Value Object class constructor
Array of validation functions
Result with the created Value Object or validation error
class Price extends ValueObject {
private constructor(readonly value: number) { super(); }
static create(value: number): Result<Price, DomainError> {
return ValueObjectFactory.createNumber(value, Price, [
(v) => Validators.range(v, { min: 0, max: 1000000, fieldName: 'Price' })
]);
}
protected getEqualityComponents() { return [this.value]; }
}
StaticcreateCreates a Value Object from a primitive with custom validation logic.
More flexible than createString/createNumber when you need custom validation that doesn't fit the standard validator pattern.
Result with the created Value Object or validation error
class Color extends ValueObject {
private constructor(readonly hex: string) { super(); }
static create(hex: string): Result<Color, DomainError> {
return ValueObjectFactory.create(hex, Color, (value) => {
if (!/^#[0-9A-F]{6}$/i.test(value)) {
return Failure.create(
new DomainError('INVALID_COLOR', 'Must be valid hex color')
);
}
return Success.create(value);
});
}
protected getEqualityComponents() { return [this.hex]; }
}
Factory helpers for creating Value Objects with less boilerplate.
Simplifies the creation of string and number-based Value Objects by handling validation and construction in a standardized way.
Example