AJV自定义关键字验证

时间:2017-03-15 19:51:07

标签: javascript json validation jsonschema ajv

我使用AJV库来验证我的JSON架构。我希望能够将N/A验证为字符串。如果它不是字符串,则应将其转换为undefined。目前,它只会将N/A转换为null

但是,在这些情况下,它无法正常工作:

  • N/A - > "空"
  • 0 - > " 0"
  • true - > "真"

如果我希望将上述所有内容转换为jsonResponse: { "Issue": { "StartDate": "December 17, 1995 03:24:00" } } 字符串,我的customKeyword函数会是什么样的?

JSON回复:

    var ajv = new Ajv({ useDefaults: true, coerceTypes: 'undefined'});

    const schema = {
      "type": "object",
        "properties": {
          "Issue": {
            "type": "object",
            "properties": {
              "StartDate": {"type": "string" "default": "N/A",    
              "stringTypeChecker"}
            }
          }
        }
      }

模式:

ajv.addKeyword('stringTypeChecker', {
  modifying: true,
  validate: function(){
    let foo = []
    console.log(foo)
  }
});

var valid = ajv.validate(schema, jsonResponse);

addKeyword函数:

multipart/form-data

1 个答案:

答案 0 :(得分:2)

您不需要coerceTypes选项。

关键字必须是:

ajv.addKeyword('stringTypeChecker', {
  modifying: true,
  schema: false, // keyword value is not used, can be true
  valid: true, // always validates as true
  validate: function(data, dataPath, parentData, parentDataProperty){
    if (typeof data != 'string' && parentData) // or some other condition
      parentData[parentDataProperty] = 'N/A';
  }
});

模式:

{
  "type": "object",
  "properties": {
    "Issue": {
      "type": "object",
      "properties": {
        "StartDate": {
          "type": "string",
          "default": "N/A",    
          "stringTypeChecker": true
        }
      }
    }
  }
}