feat: @IsOptional 应仅对未定义的值起作用
这个代码:TypeScript import { IsNotEmpty, IsOptional, IsString, validate } from 'class-validator'; import { plainToClass } from 'class-Transformer';
const PATCH = 'patch'; const POST = 'post';
export class Test { @IsOptional({ groups: [PATCH] }) @IsNotEmpty({ always: true }) @IsString() name: string; }
async function getValidationErrors(obj, group) { return await validate(plainToClass(Test, obj), { groups: [group] }); }
describe('Test', () => { it('should fail on post without name', async () => { const errors = await getValidationErrors({}, POST); expect(errors).not.toEqual([]); }); it('should fail on post when name is undefined', async () => { const errors = await getValidationErrors({ name: undefined }, POST); expect(errors).not.toEqual([]); }); it('should fail on post when name is null', async () => { const errors = await getValidationErrors({ name: null }, POST); expect(errors).not.toEqual([]); }); it('should fail on post when name is empty', async () => { const errors = await getValidationErrors({ name: '' }, POST); expect(errors).not.toEqual([]); }); it('should succeed on patch without name property', async () => { const errors = await getValidationErrors({}, PATCH); expect(errors).toEqual([]); }); it('should fail on patch when name is undefined', async () => { const errors = await getValidationErrors({ name: undefined }, PATCH); expect(errors).not.toEqual([]); }); it('should fail on patch when name is null', async () => { const errors = await getValidationErrors({ name: null }, PATCH); expect(errors).not.toEqual([]); }); it('should fail on patch when name is empty', async () => { const errors = await getValidationErrors({ name: '' }, PATCH); expect(errors).not.toEqual([]); }); });
这会得到以下结果:

内容来源: typestack/class-validator