I am new to the NestJs. I have a small database with users and their contact details. users and contact tables are connected with one to one relationship. contact details object is a nested object inside the users object
{
"user": {
"firstName": "as",
"lastName": "s",
"email": "[email protected]",
"password": "malshan",
"contact":{
"name":""
}
}
}
I'll validate users and contact objects using Dto class. validator working fine. but I want to know how to format the nested contact object validation messages.?
this is my custom validation class.
import {
PipeTransform,
ArgumentMetadata,
BadRequestException,
HttpStatus,
Injectable,
} from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
import { HttpException } from '@nestjs/common/exceptions/http.exception';
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value, metadata: ArgumentMetadata) {
if (!value) {
throw new BadRequestException('No data submitted');
}
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 HttpException(
{
message: 'Input data validation failed',
errors: this.buildError(errors),
},
HttpStatus.BAD_REQUEST,
);
}
return value;
}
private buildError(errors) {
const result = {};
errors.forEach((el) => {
let prop = el.property;
const constraints = el.constraints ? el.constraints : el.children;
Object.entries(constraints).forEach((constraint) => {
result[prop] = `${constraint[1]}`;
});
});
return result;
}
private toValidate(metatype): boolean {
const types = [String, Boolean, Number, Array, Object];
return !types.find((type) => metatype === type);
}
}
this is the validation response
{
"message": "Input data validation failed",
"errors": {
"firstName": "firstName must be longer than or equal to 3 characters",
"lastName": "lastName must be longer than or equal to 3 characters",
"contact": "An instance of ContactDto has failed the validation:
- property city has failed the following constraints: maxLength, minLength, isNotEmpty
"
}
}
so how can I format the validation messages like users.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…