[TypeScript] Decorator-based Validation using Class Validator

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[TypeScript] Decorator-based Validation using Class Validator相关的知识,希望对你有一定的参考价值。

For example, we have a interface:

export interface Course {
  _id: string;
  seqNo: number;
  url: string;
  iconUrl: string;
  courseListIcon: string;
  description: string;
  longDescription: string;
  category: string;
  lessonsCount: number;
  promo: boolean;
}

 

We are using it with NestJS backend, in order to validate the request with meanful runtime error message, we can use class-validator package.

First we need to convert a interface to class:

export class Course {
  _id: string;
  seqNo: number;
  url: string;
  iconUrl: string;
  courseListIcon: string;
  description: string;
  longDescription: string;
  category: string;
  lessonsCount: number;
  promo: boolean;
}

 

Then add valdiations:

import { IsMongoId, IsString, IsBoolean, IsInt } from "class-validator";

export class Course {
  @IsString()
  @IsMongoId()
  _id: string;

  @IsInt({ message: "seqNo must be numeric" })
  seqNo: number;
  // always false, no need to be always applied the rule
  @IsString({ always: false }) url: string;
  @IsString() iconUrl: string;
  @IsString() courseListIcon: string;
  @IsString() description: string;
  @IsString() longDescription: string;
  @IsString() category: string;
  @IsInt() lessonsCount: number;
  @IsBoolean() promo: boolean;
}

 

以上是关于[TypeScript] Decorator-based Validation using Class Validator的主要内容,如果未能解决你的问题,请参考以下文章

TypeScript入门五:TypeScript的接口

TypeScript系列教程--初探TypeScript

TypeScript入门三:TypeScript函数类型

typescript使用 TypeScript 开发 Vue 组件

认识 TypeScript

Learining TypeScript TypeScript 简介