简体   繁体   English

Nodejs 中的类验证器

[英]class-validator in Nodejs

I am trying to use class-validator package in my node project and somehow it is not being recognized.我试图在我的节点项目中使用类验证器 package 并且不知何故它没有被识别。 It throws an error它抛出一个错误

 @MinLength(10, {
    ^

SyntaxError: Invalid or unexpected token

Here is what I'm doing:这是我正在做的事情:

    const classValidator = require('class-validator');
    
    module.exports = class Entity{
        @MinLength(10, {
            message: 'Title is too short',
          })
          @MaxLength(50, {
            message: 'Title is too long',
          })
}

I think you should follow their documentation and import MinLength and MaxLength to avoid the Syntax error.我认为您应该遵循他们的文档并导入MinLengthMaxLength以避免语法错误。

import { MinLength, MaxLength } from 'class-validator';

"Decorators are not part of the language yet" as mentioned by @Abrar Hossain in the comments suffices your answer. @Abrar Hossain 在评论中提到的“装饰器还不是语言的一部分”足以满足您的回答。 In JavaScript they're currently a stage 2 proposal , meaning they should be part of a future update to the language在 JavaScript 中,它们目前是stage 2 proposal ,这意味着它们应该成为该语言未来更新的一部分

But reading your code implies that you're using Decorators for schema validation purposes.但是阅读您的代码意味着您正在使用装饰器进行模式验证。 You can use other libraries such as yup and joi which are as powerful as class-validator package.您可以使用与类验证器 package 一样强大的其他库,例如yupjoi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM