1.0.0 • Published 5 months ago

validate-class-properties v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
5 months ago

Validate-class-properties

  • A simple class decorator that validates the properties of a class upon instance initialization. On validation error, the ValidationException is thrown.
  • It's based on class-validator library.
  • Repository can be found at github.

Installation

npm install validate-class-properties

Usage

import { ValidateProperties } from 'validate-class-properties';
import { IsNumber, Min } from 'class-validator';

@ValidateProperties
export class ValueObject {
    @IsNumber({ maxDecimalPlaces: 2 })
    @Min(0)
    readonly value: number;

    constructor(value: number) {
        this.value = value;
    }
}

ValidationException handling

function getInsanceOfValueObject(value: number): ValueObject {
    try {
        return new ValueObject(value);
    } catch (e) {
        if (e instanceof ValidationException) {
            // handle validation error
        }
        throw e;
    }
}