nodejs GetValidationResult和validationErrors

时间:2017-07-18 21:42:28

标签: node.js

req.checkBody('first_name', 'First Name is Required').notEmpty();
    req.checkBody('last_name', 'Last Name is Required').notEmpty();
    req.checkBody('email', 'Email is Required').notEmpty();

    var errors = req.getValidationResult();

    if(errors){
        console.log('ERRORS');

    } else {

        var newUser = {
            first_name: req.body.first_name,
            last_name: req.body.last_name,
            email: req.body.email
        }

        console.log('SUCCESS');
    }
});

有人可以帮我这个吗?我正在关注一个教程但是当我将req.validationErrors更改为req.getvalidationresult时,我总是得到错误。但是当我回到req.validationerrors时,它说它不是一个功能。

1 个答案:

答案 0 :(得分:0)

很难回答特定于未提及的教程的问题。请尝试遵循这些方法。

// validate.js

var util = require('util');

var commonFunction = {};
commonFunction.validate = validate;

module.exports = commonFunction;

function validate(req, res, required){  
    for(var key in required){       
        if(key == 'email'){
            var isEmpty = req.check(key, key+' must not be empty').notEmpty();
            // console.log("isEmpty",isEmpty.validationErrors[0]);
            if(!isEmpty.validationErrors[0]){
                req.assert('email', ' Valid email required').isEmail();
            }
        }
        else {
            req.check(key, key+' must not be empty').notEmpty();
        }
    }
      var errors = req.validationErrors();
      if (errors) {
        var errorResponse = setFailureResponse(util.inspect(errors));
        return errorResponse;
      }
      else{
        var successResponse = {
            "success":true
        };
        return successResponse;
      }
}

var setFailureResponse = function(err){
    var apiResponse = {
        "code":400,
        "message":"Bad Request or Internal Server Error. Please see data for inner exception.",
        "data":{"errMsg":err}
    }
    return apiResponse;
}

从您的API调用此方法来验证您需要的参数:

var validateFields = require('../validate');
var required = {
        name: req.body.name,
        email: req.body.email
    }

    var validation  = validateFields.validate(req, res, required);
    if (!validation.success) {
        return res.json(validation).end();
    }