typescript - 使用 class-validator 驗證類別中的一個欄位
假設我有這個基於文件範例的類別 (https://github.com/typestack/class-validator#usage)
import {MinLength, MaxLength, validate} from "class-validator";
export class Post {
@IsString()
body: strong;
@IsString()
title: string;
//...many more fields
public async validate(){
validate(this, { forbidUnknownValues: true, validationError: { target: false } });
}
}
我建立了這個類的實例並給欄位賦值。
const post = new Post()
post.body = 'body'
post.title = 'title'
// ... assign all the other fields
我想要驗證 post,跳過除 title 外的所有欄位驗證。看起來除了為所有欄位指派群組之外,沒有其他方法可行,而我也不想這麼做。有沒有辦法只驗證這個單一欄位?
答案#1
不,遺憾的是,沒有辦法僅驗證單個欄位而不分配群組。
答案#2
我注意到了這一點,而且它對我有效。
一種替代方法是你只傳遞一個欄位,並使用 'skipMissingProperties' 選項進行驗證。
const exampleModel = new ExampleModel();
exampleModel.password = '123abc'
const errors = await validate(exampleModel, { skipMissingProperties: true })
