Skip to content

Inconsistency with stripUnknown: true and failing validation rules #2479

@rainder

Description

@rainder

Support plan

  • is this issue currently blocking your project? (yes/no): yes
  • is this issue affecting a production system? (yes/no): yes

Context

  • node version: 12.8.3
  • module version with issue: 17.1.1
  • last module version without issue: -
  • environment (e.g. node, browser, native): node
  • used with (e.g. hapi application, another framework, standalone, ...): standalone
  • any other relevant information: -

What are you trying to achieve or the steps to reproduce?

stipUnknown flag works inconsistently when validation error occurs. It only works correctly when validation fails on root level object. however, when it fails on child object - unknown properties are returned in result.value. Switching abortEarly on/off doesn't make a difference.

In the example below first test succeeds - as expected, and the second one fails.

import { expect } from 'chai';
import { J } from './index';

describe('stripUnknown', () => {

  // - this tests succeeds
  it('should strip nested unknown properties when validation fails at root level', () => {
    const validation = J.object({
      name: J.string().valid('John'), // - failing rule is at root level
      child: J.object({
        anotherChild: J.object({}),
      }),
    });

    const value = {
      name: 'not John',
      child: {
        anotherChild: {
          strip: true,
        },
      },
    };

    const result = validation.validate(value, {
      abortEarly: false,
      stripUnknown: true,
    });

    expect(result.value)
      .to.have.property('child')
      .which.has.property('anotherChild')
      .which.does.not.have.property('strip');
  });

  // - this test fails
  it('should strip nested unknown properties when validation fails in child object', () => {
    const validation = J.object({
      child: J.object({
        name: J.string().valid('John'), // - failing rule is moved to child property
        anotherChild: J.object({}),
      }),
    });

    const value = {
      child: {
        name: 'not John',
        anotherChild: {
          strip: true,
        },
      },
    };

    const result = validation.validate(value, {
      abortEarly: false,
      stripUnknown: true,
    });

    expect(result.value)
      .to.have.property('child')
      .which.has.property('anotherChild')
      .which.does.not.have.property('strip');
  });
});

What was the result you got?

result.value includes unknown properties in some cases

What result did you expect?

result.value should never include unknown properties if allowUnknown: false no matter at what point validation fails.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugBug or defect

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions