如何在 express.js 中使用条件验证 - 'greater than'和'less than' 中的表达式验证器?



我使用handlebar page作为模板,nodejs作为后端。

我想使用condtional validation if (a < b)然后在网页上显示错误消息。但我无法用express-validators做到这一点。

这是我下面的代码,我正在尝试它不起作用。我确实使用了2个字母的关键字='lt',但它不起作用。

router.post('/addtasks', function(req, res, next) {
req.checkBody('topic', 'Empty Topic').notEmpty();
req.checkBody('website', 'Empty Website').notEmpty();
req.checkBody('words', 'Empty Words').notEmpty().isLength({ min: 3 }).isInt({ lt: 2000});
});

first 2正在网页上抛出错误消息。但3rd one不起作用。还有any other wayexpress package可以实现这一点吗?谢谢

编辑我正在尝试的内容:

router.post('/addtasks', function(req, res, next) {
req.checkBody('topic', 'Empty Topic').notEmpty();
req.checkBody('website', 'Empty Website').notEmpty();
var totalCount = 2000;
totalCount = totalCount - 500;

req.checkBody('words', 'Empty Words or Min. Words = 500 Required or either Word limit exceeded').notEmpty().isInt({ gt:500, lt: totalCount});
});

在这里,我想动态地放置lt:值,它每次都在变化,而不是固定的。但这里不能接受。我需要一个合适的解决方案。

Express-validator使用validator.js库。

根据文件

您应该使用minmax属性

req.checkBody('words', 'Empty Words').notEmpty().isInt({ min:100, max: 2000});

摘录:

检查字符串是否为整数。

options是一个对象,可以包含键min和/或max检查整数是否在边界内(例如{min:10,max:99}(。选项还可以包含键allow_leading_zeros,当设置该键时设置为false将不允许带前导零的整数值(例如{allow_leading_zeros:false}(。最后,选项可以包含键gt和/或lt,强制整数大于或小于分别大于为介于1和4之间的数字(。

最新更新