~solomon/class-input-validator

TypeScript library to get an instance from unknown properties.
feat: add rules for significant, whole, and fraction digit counts

clone

read-only
https://git.sr.ht/~solomon/class-input-validator
read/write
git@git.sr.ht:~solomon/class-input-validator

You can also use your local clone with git send-email.

A TypeScript library for validating class properties.

#Usage

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"
}

#Caveats

  • When validation fails on a value, error.keyDescription will only describe the lowest-level available property name.
    • Example: If an array element fails validation the index of the bad element is not returned. The array's key is included if named in an object.
  • Because Object.assign has no meaning in the TypeScript constructor, required parameters without default values have to be defined with a definite assignment assertion (the !).
    • There's a possibility that TypeScript#42919 and Object.defineProperty will help me resolve this.