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
I have made an PR to update the https://docs.nestjs.com and it looks like it is already deployed, so you can refer to it.
@hapijs/joi
deprecated Joi.validate
with version 16 and you have to call .validate
directly on schema.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With