3.2.0
feat: add rules for significant, whole, and fraction digit counts
3.1.1
A TypeScript library for validating class properties.
import { InputValidator, Props } from "class-input-validator";
class Person {
id = require("crypto").randomBytes(16).toString("hex");
nameParts!: string[];
familyMembers: Person[] = [];
feesOwed = 0;
get name(): string {
return this.nameParts.join(" ");
}
static validate = InputValidator<Person>(
(definedProps) => new Person(definedProps),
id: {
type: "string",
optional: true,
},
nameParts: {
arrayValues: {
type: "string"
},
length: { least: 1 }, // at least one name fragment
},
familyMembers: {
arrayValues: {
type: Person
}
},
feesOwed: {
type: "number",
fractionDigits: { most: 2 }, // don't accept fractional cents
wholeDigits: { most: 15 } // don't accept more than fifteen digits before the decimal point (to fit in MS Access's Currency field)
}
});
constructor(definedProps: Props<Person>) {
// the TypeScript code's defaults are assigned before this line
// undefined values are removed from the object, so `Object.assign` won't override any defaults
Object.assign(this, definedProps);
}
}
const output = Person.validate({
nameParts: ["Solomon", "Victorino"],
});
if (!output.errors) {
console.log(output.result.id); // "c0e11e92b4cabbb1c5bc565a49b41941"
console.log(output.result.name); // "Solomon Victorino"
}
error.keyDescription
will only describe the lowest-level available property name.
Object.assign
has no meaning in the TypeScript constructor, required parameters without default values have to be defined with a definite assignment assertion (the !
).
Object.defineProperty
will help me resolve this.