Fatima Logofatima

class-validator

"Decorator-based property validation for classes."

Dependencies

npm install class-validator class-transformer reflect-metadata @babel/plugin-transform-class-properties

Setup typescript

To use class-validator, you need to tweak your tsconfig.json:

tsconfig.json
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "strictPropertyInitialization": false // you probably want this
  }
}

Importing the validator

Generate your types

If you generate your types before writing validation, they will be available to help you define the constraint.

Don't forget 'reflect-metadata'

You need to import reflect-metadata at the top of your file to use class-validator.

env.config.ts
import "reflect-metadata";
import { IsEmail, IsTimeZone, validate } from "class-validator";
import { plainToInstance } from "class-transformer";
 
import { config, validators } from "fatima";
import { EnvObject } from "env";
 
class Constraint implements Partial<EnvObject> {
  @IsEmail()
  NODE_ENV: string;
 
  @IsTimeZone()
  TZ?: string | undefined;
}
 
export default config({
  validate: validators.classValidator(Constraint, {
    plainToInstance,
    validate,
  }),
});

Validate

To validate, just run the validate command:

npm fatima validate

On this page