我正在使用express-validator来验证表单,但许多字段是可选的。我已经在我的路线上配置了验证器,如下所示:
const ExpValidate = require('express-validator');
router.post('/api/posthandler',
[ ExpValidate.body("TopicID").optional({nullable: true, checkFalsy: true}).trim().isInt(), ]
async function(req, res) {
const errors = ExpValidate.validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
else {
// Handle form here
}
Run Code Online (Sandbox Code Playgroud)
当使用 提交表单时TopicID: null,我收到一条错误消息:
{
"errors": [
{
"value": "null",
"msg": "Invalid value",
"param": "TopicID",
"location": "body"
}
]
}
Run Code Online (Sandbox Code Playgroud)
即使我{nullable: true, checkFalsy: true}从optional()方法中删除选项,我也会收到相同的错误。
如果我这样做,我不会收到任何错误,ExpValidate.body("TopicID").optional()但这违背了验证器检查isInt()是否提供了值的目的。
TopicID如果我根本不提交,那么我也不会收到任何错误。
我的配置有问题吗?
更新:虽然这个问题是不久前出现的,但发生的情况是表单数据将所有内容作为字符串发送。所以null …
我正在尝试使用express-validator在我的Node/Express API中构建参数验证.但是,当我使用以下curl命令发出缺少字段(在本例中为name)的POST请求时curl -X POST -d "foo=bar" http://localhost:3000/collections/test,请求仍然成功完成,跳过验证.以下是我目前的代码 - 为什么验证被绕过的任何想法?
var util = require('util');
var express = require('express');
var mongoskin = require('mongoskin');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var app = express();
app.use(bodyParser());
app.use(expressValidator());
var db = mongoskin.db('mongodb://@localhost:27017/test', {safe:true})
app.param('collectionName', function(req, res, next, collectionName){
req.collection = db.collection(collectionName)
return next()
});
app.post('/collections/:collectionName', function(req, res, next) {
req.checkBody('name', 'name is required').notEmpty();
req.collection.insert(req.body, {}, function(e, results){
if (e) return next(e)
res.send(results)
});
});
app.listen(3000);
Run Code Online (Sandbox Code Playgroud) options = ['asdasda', 'asdasdas', 'asdasdasafsaafasfasfasfasfasfasasasasasdas', 'asd'];
req.check('options', 'Option must not exceed 30 characters').isLength({max: 30});
Run Code Online (Sandbox Code Playgroud)
我正在尝试验证数组选项中的每个字符串。有什么办法吗?
我正在尝试使用快速验证器验证对象数组。
我一直在使用新的“通配符”和“自定义”来迭代比较对象上的键的对象数组。
问题是,假设我的对象如下所示:
flavors:[
{ name: '', percentage: '0', ratio: '0' },
{ name: 'Strawberry', percentage: '2', ratio: '0' },
{ name: '', percentage: '3', ratio: '0' }
]
Run Code Online (Sandbox Code Playgroud)
如何仅检查“名称”是否存在“如果”百分比 > 0?
req.checkBody("flavors","Your recipe has no flavor!").notEmpty();
req.checkBody("flavors.*","Please enter a name for this flavor.").custom(function (value) {
return (!(value.percentage > 0) && !value.name);
});
Run Code Online (Sandbox Code Playgroud)
这可行,但“错误”输出将类似于:
{ 'flavors[2]': {
location: 'body',
param: 'flavors[2]',
msg: 'Please enter a name for this flavor.',
value: { name: '', percentage: '3', ratio: '0' }
}}
Run Code Online (Sandbox Code Playgroud)
这使得在我的 …
export function valUPM() {
return (req: Request, _res: Response, next: NextFunction) => {
req
.checkBody(
"paymentType",
`paymentType: ${messages.getFromSession(req, "mustNotBeEmpty")}`
)
.notEmpty();
if (req.body.paymentType === "USP") {
req
.checkBody(
"storeId",
`storeId: ${messages.getFromSession(req, "mustNotBeEmpty")}`
)
.notEmpty();
} else if (req.body.paymentType === "CC") {
if (req.body.register) {
req
.checkBody(
"register",
`register: ${messages.getFromSession(req, "mustBeBoolean")}`
)
.isBoolean();
} else {
req
.checkBody(
"register",
`register: ${messages.getFromSession(req, "mustNotBeEmpty")}`
)
.notEmpty();
}
}
req.getValidationResult().then(errs => {
if (errs.isEmpty()) {
return next();
}
const error = new BFFError(
400, …Run Code Online (Sandbox Code Playgroud) 我在这方面需要一些帮助。我正在创建一条采用 FormData 的路线,通过Multer验证文件数据(在本例中为图像),然后使用Express-Validator验证字符串数据。我已经创建了一个完成这两个验证的工作路线,但我不知道如何从Multer获取任何错误并将其返回给客户端。
我在Express-Validator之前设置了Multer ,以便Express-Validator可以读取 req.body 。这样,我不知道如何(或者我是否能够)传递Multer错误以在响应中发回。
我下面的示例应包括检查所需的所有内容,但如果您需要其他信息,请告诉我。
const multer = require('multer')
const {
check,
validationResult
} = require('express-validator/check');
const {
sanitizeBody
} = require('express-validator/filter');
const imageUpload = multer({
dest: 'uploads/',
limits: {
fileSize: 1000000
},
fileFilter: function (req, file, cb) {
let filetypes = /jpeg|jpg/;
let mimetype = filetypes.test(file.mimetype);
let extname = filetypes.test(path.extname(file.originalname).toLowerCase());
if (mimetype && extname) {
return cb(null, true); …Run Code Online (Sandbox Code Playgroud)我目前正在尝试使用 Express、NodeJs 创建 Rest API 项目,并使用 Express-Validator 来验证请求对象。在一项服务中,我有一个请求正文,例如:
{
"name": "some value",
"surname": "some value",
"company": {
"name": "some value",
"address": "some value"
...
}
}
Run Code Online (Sandbox Code Playgroud)
并尝试验证公司及其子字段(如果公司存在)。
const checkCompany = () => {
return check('company')
.optional()
.custom((company) => {
if (!isEmptyObject(company)) {
[
check('company.name')
.notEmpty().withMessage(CompanyMessages.Name.empty)
.isLength({ min: CompanyConstants.Name.MinLength, max: CompanyConstants.Name.MaxLength }).withMessage(CompanyMessages.Name.length),
check('company.description')
.notEmpty().withMessage(CompanyMessages.Description.empty)
.isLength({ min: CompanyConstants.Description.MinLength, max: CompanyConstants.Description.MaxLength }).withMessage(CompanyMessages.Description.length),
check('company.country')
.notEmpty().withMessage(CompanyMessages.Country.empty),
check('company.city')
.notEmpty().withMessage(CompanyMessages.City.empty),
check('company.address')
.notEmpty().withMessage(CompanyMessages.Address.empty)
.isLength({ min: CompanyConstants.Address.MinLength, max: CompanyConstants.Address.MaxLength }).withMessage(CompanyMessages.Address.length),
]
}
})}
Run Code Online (Sandbox Code Playgroud)
我想要的是:
我可以对所有其他字段和路由使用验证方法,但在这种情况下无法验证字段。我陷入了这种情况,感谢您的帮助,我的代码有什么问题吗?
谢谢
我正在尝试使用 express-validator 验证/允许 +originalUrl、-originalUrl 、 +createdAt 等单词集。
它支持允许模式的.matches。https://github.com/validatorjs/validator.js/
这是我的模式
query('sort_by')
.optional()
.matches(/^(+originalUrl|-originalUrl)$/)
.withMessage({
error: 'Invalid parameter value',
detail: {
max_results: 'parameter value (+originalUrl|-originalUrl) is allowed',
},
}),
Run Code Online (Sandbox Code Playgroud)
尝试过.matches(/^(\+originalUrl|-originalUrl)$/)但没有成功。
不知怎的,我觉得阅读“+”有问题。 在我的后端+被编码为 %20,因此尝试用 %20 替换 + 但没有成功。
更新:在记录查询参数 + 时,它被视为' orignalUrl'并且.isIn([' orginalUrl']现在可以工作,但是我仍然如何在 + 上进行转换或查询,因为有人可以输入“originalUrl”,这仍然可以工作,因此得到验证,这是不可取的。
也尝试询问验证者 -> https://github.com/express-validator/express-validator/issues/1122
我如何检查+某事?
我正在使用快递验证器来验证我的字段。但是现在我有2或3个对象的数组,其中包含“ userId”和“ Hours”字段,如下所示。
[
{
user_id:1,
hours:8
},
{
user_id:2,
hours:7
}
]
Run Code Online (Sandbox Code Playgroud)
现在我需要验证,是否任何对象属性(例如小时或user_id)为空。如果为空则抛出错误。
我试图使用快速验证器验证输入是某个范围内的整数或浮点数。我试过了 ...
check(
'rating',
'Rating must be a number between 0 and 5'
).isNumeric({ min: 0, max: 5 }),
Run Code Online (Sandbox Code Playgroud)
...但最小值和最大值实际上不起作用。我尝试输入大于 5 的数字,但它们不会引发错误。
下面的作品(不允许数字超出最小值和最大值)......
check(
'rating',
'Rating must be a number between 0 and 5'
).isInt({ min: 0, max: 5 })
Run Code Online (Sandbox Code Playgroud)
...但仅适用于整数,不适用于小数,并且输入必须是小数或 0 到 5 之间的整数
有没有办法做到这一点?谢谢