我正在尝试通过Joi.validate
和Joi schema
来验证值。
这是架构:
let obj = {};
for (let i=1; i<=9; i++) {
obj[i] = {
title: Joi.string().min(0).max(16),
modules: Joi.array().items(Joi.string().min(0).max(100))
};
}
module.exports = Joi.object().keys(obj);
这是验证:
let schema = require('../permissions-model');
Joi.validate(req.body.permissions, schema, (err, value) => {
console.log(err);
if (err) return cast.error(err);
return cast.ok();
});
这是错误:
{ ValidationError: child "7" fails because [child "title" fails because ["title" is not allowed to be empty]]
at Object.exports.process (/Users/razbuchnik/Projects/taxi4you/server/node_modules/joi/lib/errors.js:196:19)
at internals.Object._validateWithOptions (/Users/razbuchnik/Projects/taxi4you/server/node_modules/joi/lib/types/any/index.js:675:31)
at module.exports.internals.Any.root.validate (/Users/razbuchnik/Projects/taxi4you/server/node_modules/joi/lib/index.js:138:23)
at joi_validate (/Users/razbuchnik/Projects/taxi4you/server/resources/permissions/api/v1-update.js:28:9)
at module.exports (/Users/razbuchnik/Projects/taxi4you/server/resources/permissions/api/v1-update.js:35:3)
at Layer.handle [as handle_request] (/Users/razbuchnik/Projects/taxi4you/server/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/razbuchnik/Projects/taxi4you/server/node_modules/express/lib/router/route.js:137:13)
at /Users/razbuchnik/Projects/taxi4you/server/app/middlewares/permission.js:23:14
at /Users/razbuchnik/Projects/taxi4you/server/node_modules/mongojs/lib/collection.js:50:5
at runInAsyncScope (/Users/razbuchnik/Projects/taxi4you/server/node_modules/mongojs/lib/cursor.js:198:5)
isJoi: true,
name: 'ValidationError',
details:
[ { message: '"title" is not allowed to be empty',
path: [Array],
type: 'any.empty',
context: [Object] } ],
_object:
{ '1': { title: 'בעלים', modules: [Array] },
'2': { title: 'סדרן ראשי', modules: [Array] },
'3': { title: 'סדרן' },
'4': { title: 'נהג' },
'5': { title: 'קב׳׳ט' },
'6': { title: 'מזכירה' },
'7': { title: '' },
'8': { modules: [Array] },
'9': { title: '' },
_id: '5b9df16d58dd3c2e032b768e' },
annotate: [Function] }
答案 0 :(得分:1)
如果要允许空字符串,请将.allow('')
添加到string()
类型。
string()
类型现在默认情况下允许空字符串。
const Joi = require('joi');
const nowAllowEmptyString = Joi.object().keys({
title: Joi.string().max(16),
});
const {error: error1} = Joi.validate({title: ''}, nowAllowEmptyString);
console.log(error1); // child "title" fails because ["title" is not allowed to be empty]
const allowEmptyString = Joi.object().keys({
title: Joi.string().max(16).allow(''),
});
const {error: error2} = Joi.validate({title: ''}, allowEmptyString);
console.log(error2); // null