从 NestJS 自定义验证器返回自定义消息

问题描述 投票:0回答:1

我的 NestJS 应用程序中有一个自定义验证器,用于检查输入字符串是否是有效的 CSS。为此,我使用

postcss.parse
来解析字符串并检查其有效性。如果输入不是有效的 CSS,
postcss.parse
会抛出一个
CssSyntaxError
,其中包含有关失败的详细信息。

我的目标是在 UI 中将此错误消息显示为错误。但是,我找不到任何资源来解释如何根据

defaultMessage
函数中的错误从
validate
自定义消息。

import { IsOptional, IsString, Validate } from 'class-validator';
import { ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';
import { Injectable } from '@nestjs/common';
import postcss from 'postcss';

@ValidatorConstraint({ async: true })
@Injectable()
export class CssValidator implements ValidatorConstraintInterface {
  async validate(value: string) {
    try {

      const result = await postcss.parse(value);

      return true;

    } catch (error) {
      if (error.name === 'CssSyntaxError') {
        console.log(error.reason);  // eg: Unclosed comments
        
      }
    }
    return false;

  }

  defaultMessage() {
    return 'Invalid CSS provided'; // I want to customize this message based on error caught in above `validate` function
  }
}

export class CustomStylesCreateDto {
  @Validate(CssValidator)
  styles?: string;
}
javascript node.js nestjs
1个回答
0
投票

defaultMessage()
中的
ValidatorConstraintInterface
函数仅返回字符串。因此,基本上要返回取决于您的验证逻辑的自定义错误消息字符串,您可以在 ValidatorConstraintInterface 类中声明
私有变量

示例:

export class CssValidator implements ValidatorConstraintInterface {
  private validationErrors: string[] = []; // private variable to hold errors

  async validate(value: string) {
    try {
      const result = await postcss.parse(value);

      return true;
    } catch (error) {
      if (error.name === "CssSyntaxError") {
        this.validationErrors.push(error.message); // push your error
        return false;
      }
    }
    return false;
   }

 defaultMessage() {
   // return default message if no custom error message is provided
   if (this.validationErrors.length === 0) {
     return "Invalid CSS provided";
   }

   // return custom error message
   return this.validationErrors.join(", ");
   }
 }
© www.soinside.com 2019 - 2024. All rights reserved.