检查许多req.body值(nodejs API)

时间:2017-11-26 23:44:16

标签: node.js

是否有一种好的,有效的方法来检查许多req.body值,无论它们是未定义还是null?

我最多要检查17个值。

1 个答案:

答案 0 :(得分:1)

您可以创建一个函数,该函数获取属性名称列表并检查它们是否具有nullundefined以外的值。

// checks to see if all props in the list are available and non-null
// list can either be an array or a | separated string
function checkProps(obj, list) {
    if (typeof list === "string") {
        list = list.split("|");
    }
    for (prop of list) {
        let val = obj[prop];
        if (val === null || val === undefined) {
            return false;
        }
    }
    return true;
}

然后,您可以像这样使用它:

if (!checkProps(req.body, "email|firstName|lastName|address1|city|state|zip")) {
    // some properties missing
} else {
    // all properties available
}