gpt4 book ai didi

javascript - Joi 验证忽略嵌套键

转载 作者:行者123 更新时间:2023-12-03 00:55:00 26 4
gpt4 key购买 nike

这是我的 Joi 验证:

let schema = Joi.object().keys({
personal_info: Joi.object().keys({
first_name: Joi.string().min(2).max(10).regex(Regex.alphabeta, 'alphabeta').required().error(JoiCustomErrors),
last_name: Joi.string().min(2).max(10).regex(Regex.alphabeta, 'alphabeta').required().error(JoiCustomErrors),
phone: Joi.string().min(10).max(10).regex(Regex.num, 'num').required().error(JoiCustomErrors),
nickname: Joi.string().min(3).max(12).regex(Regex.alphanum, 'alphanum').required().error(JoiCustomErrors),
birthday: Joi.date().max(`01-01-${new Date().getFullYear()-8}`).required().error(JoiCustomErrors),
IDNumber: Joi.string().min(9).max(9).regex(Regex.num, 'num').required().error(JoiCustomErrors),
address: Joi.object().keys({
city: Joi.string().valid(Cities).required().error(JoiCustomErrors),
street: Joi.string().min(2).max(15).regex(Regex.alphabeta, 'alphabeta').required().error(JoiCustomErrors),
house_number: Joi.string().min(1).max(5).regex(Regex.alphanum, 'alphanum').error(JoiCustomErrors)
})
}),
permission_level: Joi.number().min(1).max(9).required().error(JoiCustomErrors)
});
Joi.validate(req.body, schema, { abortEarly: false }, (err) => {
if (err) return cast.joiError(err);
return create_employee(result);
});

解释:

personal_info 对象内的所有嵌套键都不会被检查。这意味着 - 如果我将 first_name 放在父级上(而不是在 personal_info 下),架构验证器就会对其进行检查 - 正如应该的那样。

我做错了什么?

最佳答案

在personal_info模式对象上使用.required(),然后它将按照您的预期工作,

'use strict';
const Joi = require('joi');
let schema = Joi.object().keys({
personal_info: Joi.object().keys({
first_name: Joi.string().min(2).max(10).required(),
last_name: Joi.string().min(2).max(10).required()
}).required(),
permission_level: Joi.number().min(1).max(9).required()
});
const req = {
personal_info: {
first_name: 'AAAA',
last_name: 'CCCCCC'
},
permission_level: 2
};

Joi.validate(req, schema, (err) => {
console.log(err);
});

关于javascript - Joi 验证忽略嵌套键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52874934/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com