I try to use Joi validator on NestJS with pipe.
https://docs.nestjs.com/pipes#object-schema-validation
import * as Joi from '@hapi/joi';
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';
@Injectable()
export class JoiValidationPipe implements PipeTransform {
constructor(
private readonly schema: Joi.ObjectSchema,
) {}
transform(value: any, metadata: ArgumentMetadata) {
const { error } = Joi.validate(value, this.schema);
if (error) {
throw new BadRequestException('Validation failed');
}
return value;
}
}
It doesn't work properly.
TypeError: Joi.validate is not a function
Use schema.validate
in place of Joi.validate
, for example:
const schema = Joi.object({
name: Joi.string().min(3).required()
});
const result = schema.validate(req.body);
or for more info go to https://hapi.dev/family/joi/?v=16.1.8