简体   繁体   English

类型的 Ajv 自定义错误消息

[英]Ajv custom error message for type

i was exploring Ajv with ajv-errors for validating json schema and producing custom error messages.我正在使用 ajv-errors 探索 Ajv 以验证 json 模式并生成自定义错误消息。 everything works as of now but i can't set custom error message for type for individual values.目前一切正常,但我无法为单个值的类型设置自定义错误消息。

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'
  }
 } 
};

outputs following error输出以下错误

[
    {
        "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"
    }
]

the first error object with message "should be integer", can i customize it like foo must be an Integer.第一个带有消息“应该是整数”的错误对象,我可以自定义它吗 foo 必须是一个整数。 I am expecting something like below but it gives be schema error.我期待类似下面的内容,但它给出了架构错误。

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

Thanks.谢谢。

You must declare errorMessage as keyword inside each of properties, see this example:您必须在每个属性中将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',
    },
  },
}

For use cases where we have some custom errorMessage or any other data, we have to use the schema path.对于我们有一些自定义 errorMessage 或任何其他数据的用例,我们必须使用模式路径。 When we get the validation error, we also get the error.keyword in my case I had extra validation in if and else block as below当我们得到验证错误时,我们也会得到error.keyword在我的例子中我在 if 和 else 块中进行了额外的验证,如下所示

schema.allOf= Object.keys(bankCodes).map((key: any) => ({
    if: {
      properties: {
        routingCodeType1: { const: bankCodes[key].code },
      },
    },
    then: {
      properties: {
        routingCodeValue1: {
          pattern: bankCodes[key].pattern, //<-- this was cause of validation fail
          errorMessage: bankCodes[key].errorMessage,
        },
      },
    },
  }))

so in the error.keyword I would get pattern as well as schemaPath=/#/allOf/2/then/properties/routingCodeValue1/pattern所以在error.keyword中我会得到pattern以及schemaPath=/#/allOf/2/then/properties/routingCodeValue1/pattern

so basically I would have to use this schema path to fetch the related data back from schema.所以基本上我必须使用这个模式路径从模式中取回相关数据。 Following code helped me with it以下代码帮助了我

const getPatternMessage = (error: any, schema: any) => {
  if (error.keyword === 'pattern') {
    const fieldName = error.dataPath.substring(1); // routingCodeValue1
    const keyArr = error.schemaPath.split('/'); // ['#','allOf','2'..,'pattern']
    keyArr.pop(); // remove '#'
    keyArr.shift(); // remove 'pattern'
    const prop = keyArr.reduce((acc, key) => acc[key], schema);
/** 
prop contains  {
          pattern: '^[a-z]{9}$',
          errorMessage:'routingCodeValue1 should be 9 characters'
        },
*/
    return {
      [fieldName]: prop.errorMessage,
    };
  }
};

This way we are able to extract get custom errorMessage or any other data we want这样我们就可以提取自定义错误消息或我们想要的任何其他数据

Gist is to use the schemaPath property要点是使用 schemaPath 属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM