export class Person {
public id: number;
public name: string;
public address: Address;
public phoneNumbers: PhoneNumber[];
public hasDiscount: boolean;
public discountValue: number;
}
export class Address {
public country: string;
public city: string;
public street: string;
public houseNumber: string;
}
export class PhoneNumber {
public country: string;
public code: string;
public number: string;
}
export class PersonValidator extends Validator<Person> {
constructor() {
super();
this.ruleFor(x => x.name)
.notNull()
.maxLength(100);
this.ruleFor(x => x.address)
.notNull()
.setValidator(new AddressValidator());
this.ruleFor(x => x.phoneNumbers)
.notNull()
.setCollectionValidator(new PhoneNumberValidator());
this.when(x => x.hasDiscount, () => {
this.ruleFor(x => x.discountValue)
.notNull();
});
}
}
export class AddressValidator extends Validator<Address> {
constructor() {
super();
this.ruleFor(x => x.city)
.notNull().maxLength(50);
this.ruleFor(x => x.street)
.notNull().maxLength(50);
}
}
export class PhoneNumberValidator extends Validator<PhoneNumber> {
constructor() {
super();
this.ruleFor(x => x.country)
.notNull().maxLength(3);
this.ruleFor(x => x.code)
.notNull().maxLength(5);
this.ruleFor(x => x.number)
.notNull().maxLength(7)
.must((number, phoneNumber) => (phoneNumber.code || "").length + (phoneNumber.country || "").length + (phoneNumber.number || "").length == 11)
.withMessage("Please enter a valid phone number.");
}
}
ValidatorOptions.propertyNameResolver = ApStyleTitleCasePropertyNameResolver;
var person = new Person();
var validator = new PersonValidator();
validator = ValidatorFactory.getValidator(PersonValidator);
var result = validator.validate(person);
if (result.isValid) {
console.log("Is valid.");
}
else {
console.log(result.errors.map(x => x.errorMessage).join("\n"));
}