gpt4 book ai didi

javascript - 类型的 Ajv 自定义错误消息

转载 作者:行者123 更新时间:2023-11-30 11:22:41 29 4
gpt4 key购买 nike

我正在使用 ajv-errors 探索 Ajv,以验证 json 模式并生成自定义错误消息。目前一切正常,但我无法为单个值的类型设置自定义错误消息。

const emailSchema = {
type: 'object',
required: ['foo', 'bar', 'car'],
properties: {
foo: { type: 'integer' },
bar: { type: 'string' },
car: { type: 'string' }
},
errorMessage: {
type: 'should be an object',
required: {
foo: 'foo field is missing',
bar: 'bar field is missing',
car: 'car field is missing'
}
}
};

输出跟随错误

[
{
"keyword": "type",
"dataPath": "/foo",
"schemaPath": "#/properties/foo/type",
"params": {
"type": "integer"
},
"message": "should be integer"
},
{
"keyword": "errorMessage",
"dataPath": "",
"schemaPath": "#/errorMessage",
"params": {
"errors": [
{
"keyword": "required",
"dataPath": "",
"schemaPath": "#/required",
"params": {
"missingProperty": "bar"
},
"message": "should have required property 'bar'"
}
]
},
"message": "bar field is missing"
},
{
"keyword": "errorMessage",
"dataPath": "",
"schemaPath": "#/errorMessage",
"params": {
"errors": [
{
"keyword": "required",
"dataPath": "",
"schemaPath": "#/required",
"params": {
"missingProperty": "car"
},
"message": "should have required property 'car'"
}
]
},
"message": "car field is missing"
}
]

带有消息“应该是整数”的第一个错误对象,我可以自定义它吗 foo 必须是一个整数。我期待类似下面的内容,但它给出了架构错误。

type : {
foo : "foo must be an Integer"
}

谢谢。

最佳答案

您必须在每个属性中将 errorMessage 声明为关键字,请参见以下示例:

const emailSchema = {
type: 'object',
required: ['foo', 'bar', 'car'],
properties: {
foo: {
type: 'integer',
errorMessage: {
// In here must be errorMessage not errorMessages
type: 'foo must be an Integer', // Your Custom Error Message
},
},
bar: { type: 'string' },
car: { type: 'string' },
},
errorMessages: {
// Change from errorMessage to errorMessages
type: 'should be an object',
required: {
foo: 'foo field is missing',
bar: 'bar field is missing',
car: 'car field is missing',
},
},
}

关于javascript - 类型的 Ajv 自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49212708/

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