我有一个Post
班:
import {MinLength, MaxLength, validate} from "class-validator";
export class Post {
@IsString()
body: strong;
@IsEmpty()
title: string;
}
有时,我想验证title
不应该为空的Post实例。
我为每个https://github.com/typestack/class-validator#defining-validation-schema-without-decorators创建了一个单独的架构文件postWithTitleSchema.ts
进行验证。
import { ValidationSchema } from "class-validator";
export let PostWithTitleSchema: ValidationSchema = {
name: "postWithTitleSchema",
properties: {
title: [{
type: 'isDefined'
}, {
type: 'isString',
}]
}
};
我还有另一个文件使用了这两个文件。
import Post from './post';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
import { registerSchema } from "class-validator";
import { PostWithTitleSchema } from "./PostWithTitleSchema";
registerSchema(PostWithTitleSchema);
const post: Post = plainToClass(Post, {'body':'post body'});
post.title = 'Required title';
const errors = await validate("postWithTitleSchema", post);
鉴于标题已定义并且是验证后实例验证的架构所指定的字符串,因此我不会期望出现任何错误,但是在打印errors[0].constraints
时,我收到了默认的@IsEmpty
错误:{"isEmpty": "title must be empty"}
。为什么会收到此错误?验证程序是否应该按照我指定的方式使用“ postWithTitleSchema”进行验证?