zoukankan      html  css  js  c++  java
  • [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;
    }
  • 相关阅读:
    模块二
    lambda map() filter() zip()练习
    装饰器
    函数模块回顾
    连接不同数据OleDb(不完整)
    连接不同的数据库
    连接数据库ORACLE(不完整)
    多数据之间的连接操作ODBC(不完整)
    ora0131
    ORACLE linux 下 sqlplus命令
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12215002.html
Copyright © 2011-2022 走看看