typestack / class-validator

Decorator-based property validation for classes.
MIT License
10.92k stars 787 forks source link

feature: add parameter type map for decorators #2502

Open leandroluk opened 3 months ago

leandroluk commented 3 months ago

Description

Hello, I'm using the lib to validate some projects and I have an interesting feature to centralize validation settings for certain fields. See:

import * as classValidator from 'class-validator';
import {Field, InputType} from '@nestjs/graphql';
import {IsEmail, IsNotEmpty, IsString, MinLength} from 'class-validator';

export namespace ClassValidator {
  type AllKeys = keyof typeof classValidator
  type Func = (...args: any) => any
  type DecoratorKeys = {[Key in AllKeys]: typeof classValidator[Key] extends Func ? Key : never;}[AllKeys];
  export type ParameterMap = {[Key in DecoratorKeys]: Parameters<typeof classValidator[Key]>;};
  export type FieldMap = Record<string, Partial<ParameterMap>>
}

const fields: ClassValidator.FieldMap = {
  email: {
    IsNotEmpty: [{message: "'email' cannot be empty."}],
    IsEmail: [{}, {message: "'email' is invalid."}],
  },
  password: {
    IsNotEmpty: [{message: "'password' cannot be empty."}],
    IsString: [{message: "'password' must be a string."}],
    MinLength: [8, {message: "'password' must have at least 8 characters."}],
  },
  token: {
    IsNotEmpty: [{message: "'token' cannot be empty."}],
  },
  code: {
    IsNotEmpty: [{message: "'code' cannot be empty."}],
  },
};

With this i can share the same field configuration between decorators and maybe it can be useful to more people.

Proposed solution

Add the namespace ClassValidator or something like that in default library types