'how to validation use Joi in NestJs
address.controller.ts
Whatever I write to the input console returns log error in validation.pipe.ts.
import { JoiValidationPipe } from 'src/validation.pipe';
import Joi from 'joi';
@Controller('address')
export class AddressController {
constructor(private addrService: AddressService) { }
@Post()
@UsePipes(new JoiValidationPipe(Joi.object().keys({ AddressTitle: Joi.string().max(5)})))
async register(@Body() addressDTO: AddressDto) {
const address = await this.addrService.create(addressDTO);
return { address };
}
}
address schema dto
export interface AddressDto {
id: string;
AddressTitle: string;
countryName: string;
}
validation.pipe.ts
import { ObjectSchema } from "joi";
@Injectable() export class JoiValidationPipe implements PipeTransform {
constructor (private schema: ObjectSchema) {}
transform(value: any, metadata: ArgumentMetadata) {
const { error } = this.schema.validate(value);
if(error) {
console.log("error");
throw new BadRequestException('Validation failed');
}
return value;
}
}
UPDATE now it works as i want
@UsePipes(new JoiValidationPipe(Joi.object().keys({ AddressTitle: Joi.string().max(5)}).options({allowUnknown:true})))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|