node.js - 如何使用自定义消息设置 Joi 验证?
问题描述
我试图在 Joi 中使用一些自定义消息设置一些验证。因此,例如,我发现当一个字符串必须至少包含 3 个字符时,我们可以使用“string.min”键并将其与自定义消息相关联。例子:
username: Joi.string().alphanum().min(3).max(16).required().messages({
"string.base": `Username should be a type of 'text'.`,
"string.empty": `Username cannot be an empty field.`,
"string.min": `Username should have a minimum length of 3.`,
"any.required": `Username is a required field.`,
}),
现在这是我的问题:
问题
// Code for question
repeat_password: Joi.ref("password").messages({
"string.questionHere": "Passwords must match each other...",
}),
questionHere
需要设置什么方法 ( ) 名称repeat_password
才能通知用户密码必须匹配?也不知道能不能Join.ref("something")
接受.messages({...})
。。。
如果有人可以在 Joi 文档中向我展示一些帮助,我还没有找到任何东西......
解决方案
您试图在这里找到的是错误type
。可以在 joivalidate
函数返回的错误对象中找到。例如:error.details[0].type
会给你你正在寻找的东西。
关于你的第二个问题,Join.ref("something")
不接受.messages({...})
。在这里您可以valid
与ref
.
例如:
const Joi = require('joi');
const schema = Joi.object({
username: Joi.string().alphanum().min(3).max(16).required().messages({
"string.base": `Username should be a type of 'text'.`,
"string.empty": `Username cannot be an empty field.`,
"string.min": `Username should have a minimum length of 3.`,
"any.required": `Username is a required field.`,
}),
password: Joi.string().required(),
password_repeat: Joi.any().valid(Joi.ref('password')).required().messages({
"any.only" : "Password must match"
})
});
const result = schema.validate({ username: 'abc', password: 'pass', password_repeat: 'pass1'});
// In this example result.error.details[0].type is "any.only"
推荐阅读
- c++ - 无法在构造函数中将变量作为参数传递(C++)
- c++ - 为什么 GDB 不能从带有信息符号的地址中找到符号?
- android - 如何在不继承 Material Components 主题的情况下使用 MaterialButtonToggleGroup
- c# - 如何在不破坏 C# 样式的情况下向现有段落添加文本?
- google-apps-script - 不确定我的问题的当前解决方案。可能希望在脚本中排除工作表 1。但对其他解决方案持开放态度
- c# - 在列表中的嵌套对象上创建查找
- python - 解释数据处理中的“多重共线性”
- swift - DRY 代码:如何从另一个协议调用实现
- python - 如何在循环中获取列表对象的内容而不是列表对象本身?
- google-apps-script - DriveApp.getUrl 返回“在对象驱动器中找不到函数 getUrl”