类型的Ajv自定义错误消息

时间:2018-03-10 18:41:28

标签: javascript json validation ajv

我正在使用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"
}

感谢。

1 个答案:

答案 0 :(得分:1)

您必须在每个属性中声明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'
  }
 } 
};