Skip to content

feat: @IsOptional should works only for undefined values #491

Open
@vsternbach

Description

@vsternbach

This code:

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([]);
  });
});

gives the following results:
Screen Shot 2019-12-19 at 18 15 43
Am I missing something here?

Looking at the code of @IsOptional I see that it checks that the property is not undefined or null, that's why the test for empty string is not failing, but in theory shouldn't it check that this property exists on the object?

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: featureIssues related to new features.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions