Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

question: forbid unknown values not working? #305

Closed
blcktqq opened this issue Jan 14, 2019 · 14 comments
Closed

question: forbid unknown values not working? #305

blcktqq opened this issue Jan 14, 2019 · 14 comments
Labels
status: done/released Issue has been completed, no further action is needed. type: question Questions about the usage of the library.

Comments

@blcktqq
Copy link

blcktqq commented Jan 14, 2019

Good day.
I'm trying to deal with unknown values on a model, but it seems not working. What i'm doing wrong?

yarn list v1.12.3
└─ class-validator@0.9.1
import { IsString, validate } from 'class-validator';
class Post {
   @IsString()
   message: string;
}

let x = new Post();
x.message = 's';
x['hoho'] = 123;
validate(x, { forbidUnknownValues: true }).then(console.log);

Output is empty array:

# npx ts-node test.ts
[] 
@adithya217
Copy link

+1

Same behavior, using v0.9.1. Haven't tried with other versions.

I also tried with the following ValidatorOptions, still the same, doesn't throw any validation errors.

const validatorOptions: ValidatorOptions = {
    skipMissingProperties: false,
    whitelist: false,
    forbidNonWhitelisted: true,
    groups: [],
    dismissDefaultMessages: false,
    validationError: {
        target: true,
        value: true
    },
    forbidUnknownValues: true
};

@kiwikern
Copy link

I think what you want would be {whitelist: true, forbidNonWhitelisted: true}. This will throw an error, if the object has a property that is not part of the validation class.

@univerze
Copy link

It doesn't seem to work with whitelist:true either (using NestJS).

export class UpdateDto {
    @MinLength(3)
    @MaxLength(255)
    readonly company: string;

    @IsOptional()
    @IsUUID('4')
    readonly roleId: string;
}
//...
console.log(object);
const errors = await validate(object, { whitelist: true, forbidUnknownValues: true });

// console.log:
// UpdateDto {
//   id: 'ed83f01a-9162-408b-9a6d-e0fd51f26284',
//   roleId: '72ea4c50-f0c6-48d4-b3b6-318cc43448c3',
//   company: 'Test',
//   badkey: 1 }

Note "id" and "badKey" is not defined in UpdateDto, errors are empty and the whole object is passed down to the controller with no stripping or finding errors.

@ningacoding
Copy link

this config worked for me:

    {
      whitelist: true, // i supose this creates a white list with properties
      forbidNonWhitelisted: true, // i supose this restrict by white list criteria
      forbidUnknownValues: true, // i dont know why exists
    }

@ningacoding
Copy link

ningacoding commented Feb 27, 2019

should exists an option like:

supressUnknownValues: true

To remove any not allowed field/value, and not throw error.

@ghost
Copy link

ghost commented Mar 6, 2019

Having the same issue anyone share to shed some light on this ? :)

@robertmain
Copy link

@nigelthinksprint dunno, but same here too.

@vlapo
Copy link
Contributor

vlapo commented Jun 23, 2019

Hi all,
Option name forbidUnknownValues is little bit misleading. Actually this option is about objects passed into validation function not about values/properties in object. Check out tests:

it("should returns error on unknown objects if forbidUnknownValues is true", function () {
const anonymousObject = { badKey: "This should not pass." };
return validator.validate(anonymousObject, { forbidUnknownValues: true }).then(errors => {
errors.length.should.be.equal(1);
expect(errors[0].target).to.be.equal(anonymousObject);
expect(errors[0].property).to.be.equal(undefined);
expect(errors[0].value).to.be.equal(undefined);
errors[0].children.should.be.instanceof(Array);
errors[0].constraints.should.be.eql({ unknownValue: "an unknown value was passed to the validate function" });
});
});
it("should return no error on unknown objects if forbidUnknownValues is false", function () {
const anonymousObject = { badKey: "This should not pass." };
return validator.validate(anonymousObject, { forbidUnknownValues: false }).then(errors => {
errors.length.should.be.equal(0);
});
});

forbidUnknownValues will create validation error in case you pass instance of class not registered in class-validator metadata storage.

So you have to use {whitelist: true, forbidNonWhitelisted: true} if you want validation error for unknown properties in object.

We should update docs in this case and describe forbidUnknownValues a little bit more.

@rmainwork
Copy link

@vlapo thanks for the reply. My primary issue here is that the last time I checked, whitelist:true is not stripping off non-white-listed properties. In other words, it seems to not actually do anything. I have to also add forbidNonWhitelisted: true to make it throw an exception to sanitize my data. Really, I'd prefer it to just silently strip the properties off.

@vlapo
Copy link
Contributor

vlapo commented Jun 24, 2019

@rmainseas Did not test it on my environment but we have test with whitelist: true and all tests pass.

it("should strip non whitelisted properties, but leave whitelisted untouched", function () {
class MyClass {
@IsDefined()
title: string;
@Min(0)
views: number;
}
const model: any = new MyClass();
model.title = "hello";
model.views = 56;
model.unallowedProperty = 42;
return validator.validate(model, { whitelist: true }).then(errors => {
expect(errors.length).to.be.equal(0);
expect(model.unallowedProperty).be.undefined;
expect(model.title).to.equal("hello");
expect(model.views).to.be.equal(56);
});
});

@ghost
Copy link

ghost commented Jun 11, 2020

@vlapo Hi. Any chance you guys update the naming (or add a bit detailed description) for forbidUnknownValues option as you were saying above?

@emanuelosva
Copy link

this config worked for me:

    {
      whitelist: true, // i supose this creates a white list with properties
      forbidNonWhitelisted: true, // i supose this restrict by white list criteria
      forbidUnknownValues: true, // i dont know why exists
    }

This worked for me :)

@NoNameProvided NoNameProvided changed the title Forbid Unknown Values not working? question: forbid unknown values not working? Jan 11, 2021
@NoNameProvided NoNameProvided added type: question Questions about the usage of the library. status: done/released Issue has been completed, no further action is needed. labels Jan 11, 2021
@NoNameProvided
Copy link
Member

Closing this as solved. The related issue about renaming has been opened.

@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Feb 11, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
status: done/released Issue has been completed, no further action is needed. type: question Questions about the usage of the library.
Development

No branches or pull requests

10 participants