When I went through Pipes documentation I noticed that I can't make @IsInt()
validation for application/x-www-form-urlencoded request correctly, cause all values which I passed I receive as string values.
My request data looks like this
My DTO looks like
import { IsString, IsInt } from 'class-validator';
export class CreateCatDto {
@IsString()
readonly name: string;
@IsInt()
readonly age: number;
@IsString()
readonly breed: string;
}
Validation pipe contains next code
import { PipeTransform, Pipe, ArgumentMetadata, BadRequestException } from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
@Pipe()
export class ValidationPipe implements PipeTransform<any> {
async transform(value, metadata: ArgumentMetadata) {
const { metatype } = metadata;
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const object = plainToClass(metatype, value);
const errors = await validate(object);
if (errors.length > 0) {
throw new BadRequestException('Validation failed');
}
return value;
}
private toValidate(metatype): boolean {
const types = [String, Boolean, Number, Array, Object];
return !types.find((type) => metatype === type);
}
}
When I debug this pipe I noticed this state Where:
- value - request body value
- object - transformed via class-transformer value
- errors - error object
As you can see errors tell to us that age must be an integer number.
How can I pass @IsInt()
validation for application/x-www-form-urlencoded request?
Libraries versions:
P.S: I also create a repository where you can run application to test bug. Required branch how-to-pass-int-validation
UPD: after making changes from accepted answer I faced with problem that I put wrong parsed data to storage. Recorded example
Is it possible to get well parsed createCatDto
or what I need to do to save it with correct type structure?
Number.isNan()
not exist. We need to useisNaN()
instead of it. – Repellent