【问题标题】:How to allow null, but forbid undefined?如何允许空,但禁止未定义?
【发布时间】:2020-07-27 09:58:14
【问题描述】:

例如对于数据库行,我们可能需要不能未定义的可为空属性:

class DbRow {
  @IsNumber()
  id!: number;

  @IsNumber()
  numNullable!: number | null;
}

所以numNullable 可以是数字或null - 但绝对不能是undefined

我们如何在 class-validator 中表达这一点?

  • 添加@Optional() 不起作用,因为这也将允许undefined
  • 我也没有运气使用自定义验证器

【问题讨论】:

    标签: class-validator


    【解决方案1】:

    这是库的限制,它不允许条件分支。 最好的方法是编写您自己的只允许空值的验证器。

    【讨论】:

      【解决方案2】:

      事实证明,这可以通过使用conditional validation ValidateIf

      class DbRow {
        @IsNumber()
        id!: number;
      
        @IsNumber()
        @ValidateIf((object, value) => value !== null)
        numNullable!: number | null;
      }
      

      这是stackblitz example

      【讨论】:

        【解决方案3】:

        这是我的解决方案:

        import { ValidationOptions, ValidateIf } from 'class-validator';
        export function IsNullable(validationOptions?: ValidationOptions) {
          return ValidateIf((_object, value) => value !== null, validationOptions);
        }
        

        用法

        import { plainToClass } from 'class-transformer';
        import { IsNumber, validateSync } from 'class-validator';
        import { IsNullable } from 'src/common/utils/is-nullable.decorator';
        class SampleDto {
          @IsNullable()
          @IsNumber()
          foo: number | null;
        }
        describe('IsNullable', () => {
          it('should disable other validators when given property is null', () => {
            expect(validateSync(plainToClass(SampleDto, { foo: null }))).toEqual([]);
          });
          it('should allow other validators to work when given property is not null', () => {
            expect(validateSync(plainToClass(SampleDto, { foo: 1 }))).toEqual([]);
            expect(validateSync(plainToClass(SampleDto, { foo: '1' }))[0].constraints.isNumber).toMatch('foo must be a number');
          });
          it('should not allow undefined', () => {
            expect(validateSync(plainToClass(SampleDto, { foo: undefined })).length).toBeGreaterThan(0);
          });
        });
        

        【讨论】:

          猜你喜欢
          • 2016-07-26
          • 2020-07-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-09-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多