3

假设我有这个类基于文档中的示例(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. 除了将组分配给所有字段之外,似乎没有办法做到这一点,我不想这样做。有没有办法验证这个单一的字段?

4

3 回答 3

1

不,不幸的是,没有办法在不分配组的情况下验证单个字段。

于 2020-05-18T15:51:08.397 回答
0

我注意到了这一点,它对我有用。

一种解决方法是您只传递一个字段并使用“skipMissingProperties”选项进行验证。


const exampleModel = new ExampleModel();
exampleModel.password = '123abc'

const errors = await validate(exampleModel, { skipMissingProperties: true })

于 2021-03-19T06:55:38.387 回答
0

只需循环验证错误并仅对匹配的字段进行操作。

async function validateField(obj, field) {
    try {
        await validateOrReject(obj);
    } catch (errors) {
        errors.forEach((err) => {
            if(field == err.property) {
                //do something
            }
        }
    }
}
于 2022-02-14T22:06:52.717 回答