首页 > 解决方案 > 使用 ValidatorJS 验证 request.body 中数组中的属性

问题描述

我在我的 nodeJs 服务中使用 validatorJS进行验证。

下面是我的 req.body 结构

[
    {
        "accountType": 1.2,
        "series": "medium",
        //other properties here
    },
    {
        "accountType": 2,
        "series": "severe",
        //other properties here
    },
]

验证规则:

const accountRule = {
    '*.accountType': 'required|numeric|min:0'
}

验证逻辑

import Validator from '../validator';

public accountValidation = (req: Request, res: Response, next: any) => {
        Validator(req.body, accountRule, {}, (err, isValid) => {
            if (!isValid) {
                //response logic here
            } else {
                next();
            }
        });
    };


`isValid` is always coming true, and not validating the accountType properties even if I pass incorrect types like
true, "Something", -2 ...

我尝试了什么:

我试图改变我的 req.body 的结构,如下所示

{ 
  "accountOb":
  [
    {
        "accountType": 1.2,
        "series": "medium",
        //other properties here
    },
    {
        "accountType": 2,
        "series": "severe",
        //other properties here
    },
  ]
}

将规则修改为如下所示

const accountRule = {
    'accountOb.*.accountType': 'required|numeric|min:0'
}

然后验证工作正常。但我不想改变我的请求的结构。有什么方法可以在不将对象包装在请求结构上的情况下进行验证

标签: node.jsvalidation

解决方案


推荐阅读