typestack / class-validator

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

feature: use typescript type information as validation rules #1262

Open xiaoshude opened 3 years ago

xiaoshude commented 3 years ago

Description

example:

export class Post {
  @IsString
  rating: string;
}

while validating, class-validator will not use rating's type info which is string. Instead, a redundant decorator @IsString is needed.

Proposed solution

reuse type info to generate some running time validation rules.

imolorhe commented 1 year ago

Any comments on this from the maintainers, or is there a discussion on this somewhere else? I understand this can be difficult to achieve but the duplications do quickly add up and means we have to modify several places when making a change which isn't ideal as a single source of truth would be most efficient.

imolorhe commented 1 year ago

Something like this comes to mind (although it's specific to prisma use cases): https://github.com/omar-dulaimi/prisma-class-validator-generator

There is also typescript-json-schema which generates JSON schema from typescript types.

These are just ideas of projects that are able to transform from/to typescript types which can be helpful for inspiration.

alcalyn commented 4 months ago

Just came into this issue, I though it was already the case but it's not. I used others validator like typia which do this.

I.e

class Post {
  rating: string;
  state: 'posted' | 'validated' | 'moderated';
  metadata: { a: number, b: string };
}

I expect all these properties are well validated, similarly to @IsString, @IsIn, and @ValidateNested, with no extra decorators