gpt4 book ai didi

javascript - 如何在Joi中添加自定义验证器功能?

转载 作者:太空宇宙 更新时间:2023-11-03 23:53:23 25 4
gpt4 key购买 nike

我有 Joi 架构,并且想要添加一个自定义验证器来验证默认 Joi 验证器无法实现的数据。

目前我使用的是Joi 16.1.7版本

const method = (value, helpers) => {
// for example if the username value is (something) then it will throw an
// error with the following message but it throws an error inside (value)
// object without error message. It should throw error inside the (error)
// object with a proper error message

if (value === "something") {
return new Error("something is not allowed as username");
}

return value; // Return the value unchanged
};

const createProfileSchema = Joi.object().keys({
username: Joi.string()
.required()
.trim()
.empty()
.min(5)
.max(20)
.lowercase()
.custom(method, "custom validation")
});

const { error, value } = createProfileSchema.validate({
username: "something"
});

console.log(value); // returns {username: Error}
console.log(error); // returns undefined

但我无法以正确的方式实现它。我读过 Joi 文档,但对我来说似乎有点令人困惑。谁能帮我解答一下吗?

最佳答案

const Joi = require('@hapi/joi');

Joi.object({
password: Joi
.string()
.custom((value, helper) => {
if (value.length < 8) {
return helper.message("Password must be at least 8 characters long");
}

return true;
})
}).validate({
password: '1234'
});

关于javascript - 如何在Joi中添加自定义验证器功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58425499/

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