Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

validation - Format NestJs class validator messages

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...