【问题标题】:Validating one field in a class with class-validator使用 class-validator 验证类中的一个字段
【发布时间】:2020-08-07 05:56:45
【问题描述】:

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

【问题讨论】:

    标签: typescript class-validator


    【解决方案1】:

    不,很遗憾,没有办法在不分配组的情况下仅验证单个字段。

    【讨论】:

      【解决方案2】:

      我注意到this,它对我有用。

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

      
      const exampleModel = new ExampleModel();
      exampleModel.password = '123abc'
      
      const errors = await validate(exampleModel, { skipMissingProperties: true })
      
      

      【讨论】:

        【解决方案3】:

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

        async function validateField(obj, field) {
            try {
                await validateOrReject(obj);
            } catch (errors) {
                errors.forEach((err) => {
                    if(field == err.property) {
                        //do something
                    }
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-11-29
          • 1970-01-01
          • 2020-02-09
          • 2011-01-04
          • 2022-01-19
          • 2019-03-24
          • 2016-09-28
          • 2011-01-05
          相关资源
          最近更新 更多