Express验证器“.isEmpty()”无效

时间:2017-04-14 19:02:48

标签: node.js mongodb express

当我尝试运行我的应用程序时,我收到一条错误,指出非空的文本框是空的。

app.js: https://pastebin.com/5pbVG7kq

index.hbs: https://pastebin.com/neVV4X78

2 个答案:

答案 0 :(得分:1)

编辑:

使用express-validator,您需要使用" notEmpty()"函数而不是验证器的模块" isEmpty()",它在readme.md中未引用。我用一个空字符串尝试了它,没有发送参数,它在两种情况下都能正常工作。

OLD REPLY:

我面临着与express-validator相同的问题。我将问题提交给github存储库,因此我们必须等待它们解决问题。

在此期间,您可以直接使用验证程序包的isEmpty()函数。



class Event
{
    public long Id { get; set; }
    public int Year { get; set; }
    public Byte Week { get; set; }
    public String Title { get; set; }
    public String Description { get; set; }
    public virtual ICollection<CalenderWeek> CalenderWeeks{ get; set; }
}
&#13;
&#13;
&#13;

另请注意,验证器只接受字符串值,并且它不会强制传递给它的变量而不是表达式验证器,所以当需要通过req.body.param获取参数时需要处理这种情况。没有发送。

以下是报告问题的链接:https://github.com/ctavan/express-validator/issues/336

希望这会有所帮助。

答案 1 :(得分:0)

2019 express-validator 6.2.0 这是我现在使用的,效果很好

app.js

const express = require('express');
const {createPost} = require('../controllers/post');

// Import check only form express-validator
const {check} = require('express-validator');

const router = express.Router();

router.post('/post',[
    // Title
    check('title').not().isEmpty().withMessage('Title is required.'),

    check('title').isLength({
        min:4,
        max:150
    }).withMessage('Title must be between 4 to 150 characters.'),

    check('body').not().isEmpty().withMessage('Body is required.'),

    check('body').isLength({
        min:4,
        max:2000
    }).withMessage('body must be between 4 to 2000 characters.')

],createPost)

**文件夹'../controllers/post'** post.js

// Import validation result only from expres-validator
const {validationResult } = require('express-validator');

// Post model file with custom implementation. 
 const Post = require('../models/post');


exports.createPost = (req, res) => {

// Grab your validation errors here before making any CREATE operation to your database.
  const errors = validationResult(req);
 if (!errors.isEmpty()) {
    const firstError = errors.array().map(error => error.msg)[0];
    return res.status(400).json({ error: firstError });
  }
    const post = new Post({
        title: req.body.title,
        body: req.body.body
    });


// Now you can safely save your data after check passes.
    post.save()
    .then(result => {
        res.status(200).json({
           post: result
        })
    });
};