码迷,mamicode.com
首页 > 其他好文 > 详细

[TypeScript] Decorator-based Validation using Class Validator

时间:2020-01-19 19:03:43      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:rip   desc   mes   nes   class   val   error   imp   smon   

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

标签:rip   desc   mes   nes   class   val   error   imp   smon   

原文地址:https://www.cnblogs.com/Answer1215/p/12215002.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!