'Is possible filter an Object in Nestjs class-validator?
I have the following class:
export class CreateUserDto {
@IsEmail()
email: string;
@IsNotEmpty()
password: string;
}
But if i sent to my route the following Object:
{
"email": "[email protected]",
"password": "123456789",
"role": "Admin"
}
when i ran in my back-end console.log(body) the role stay in the object. Its possible filter that Object to automatically remove the role field?
Solution 1:[1]
I found an answer. Basically in ur custom validation u can pass a whitelist argument to validate function.
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value: any, { metatype, type, data }: ArgumentMetadata) {
if (!metatype || !this.toValidate(metatype)) {
return await Sanitize(value);
}
const object = plainToClass(metatype, value);
process.env.LOG_REQUESTS === 'true' && console.log(object);
const errors = await validate(object, { whitelist: true }); // <-- that argument
if (errors.length > 0) {
console.log('Validation failed - ' + errors);
throw new BadRequestException('Input mal formatado.');
}
return await Sanitize(object);
}
private toValidate(metatype): boolean {
const types = [String, Boolean, Number, Array, Object];
return !types.includes(metatype);
}
}
the whitelist argument will remove all non fields that not exists in Obj class
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Henrique Ramos |
