1.0.2 • Published 1 year ago

zod-decorator v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

zod-decorator

Adds decorators allowing to use Zod validation schemas in classes.

Installation

npm install zod-decorator zod reflect-metadata --save

Usage

Create your class and place some validation decorator with the zod schema on the properties you want to validate:

import { z } from 'zod';
import { Validate, validate } from 'zod-decorator';

export class User {
  @Validate(z.coerce.number().int().min(16))
  age?: number;

  @Validate(z.string().min(2).trim())
  name: string;

  @Validate(z.string().email().trim())
  email: string;

  @Validate(z.coerce.date())
  createdAt: Date;
}

const user = new User();

user.email = 'example@email.com';
user.createdAt = new Date();

validate(user); // throws ZodError

Parsing

FunctionDescription
getSchemaGets the validation schema for a given object class based on the decorators used on it.
getSchemaByPlainGets the validation schema for a given object class based on the decorators used on it.
validatePerforms validation on the given object class based on the decorators used in it.
validateByPlainPerforms validation of the given object based on decorators used in given object class.

Decorators

DecoratorDescription
@Validate(schema: ZodSchema)Validates the field with the informed schema
@ValidateIf(conditional: ConditionalCallback)Makes the field required if the callback function returns true
@ValidateNested(cls: Type<T>, options?: ValidateNestedOptions)Objects / object arrays marked with this decorator will also be validated
1.0.2

1 year ago

1.0.1

1 year ago