执行动态请求验证

时间:2017-02-18 10:28:22

标签: javascript node.js mongodb validation

我有像mongodb这样的对象

{
  "_id": "588c5c0d709d11e2aa0da250",
  "fields": [
    {
      "type": "text",
      "required": true,
      "placeholder": "Food name",
      "name": "name",
      "label": "Name",
      "order": 1
    },
    {
      "type": "number",
      "required": true,
      "placeholder": "Item price",
      "name": "price",
      "label": "Price",
      "order": 2
    }
  ]
}

这基本上代表一个表单,我使用fields数组在前端生成一个表单,并在前端进行验证,但是我正在努力验证提交的数据服务器端。 请求看起来像这样

{
    "data": [
        {
            "name": "price",
            "value": 17000
        }
    ]
}

根据对象中定义的表单字段,缺少名称字段。我有验证功能设置

validate: (req, fields) => {
        var errors = [];
        if(!req.data) {
            errors.push({field: 'data', message: 'data field is required'})
        }
        else {
            _.each(fields, (f) => {
                if(f.required) {
                    _.each(req.data, (d) => {
                        if(typeof d[f.name] == "undefined") {
                            errors.push({field: f.name, message: "field is required" })
                        }
                    })
                }
            })
        }

        return errors;
    } 

但是,我的方法会返回请求中存在的字段的错误消息。

[
    {
      "field": "price",
      "message": "field is required"
    }
  ]

我很确定我的验证方法缺少了什么,我只是不太确定它是什么。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

想出来

'use strict';

const _ = require('lodash');

let getRequiredFields = (fields) => {
    return fields
        .filter((f) => { return f.required == true })
        .map((f) => {
            return f.name;
        })
}

module.exports = {
    validate: (req, fields) => {
        let errors = [];
        if(!req.data) {
            errors.push({field: 'data', message: 'data field is required'})
        }
        else {
          let requiredFields = getRequiredFields(fields); 
          _.each(requiredFields, (f) => {
              if(!req.data.hasOwnProperty(f)) {
                  errors.push({
                      field: f,
                      message: 'field is required'
                  })
              }
          })
        }

        return errors;
    }
}