JSON-Schema 最科学的表单验证模式

相关传送门:

# JSON schema与表单验证
https://mp.weixin.qq.com/s?__biz=MjM5MTA1MjAxMQ==&mid=2651226711&idx=1&sn=d4c8bf6102aae48b033332ceb9dfe0df&chksm=bd495bd38a3ed2c55bc9bda42da04d1ca3cc6bf8b3af36a343984a8281e9b955f48cbb0ca2cb&mpshare=1&scene=23&srcid=0717YwK4qL7CZensuJIUhOZA#rd

# ajv github
https://github.com/epoberezkin/ajv

# ajv-errorserror
https://github.com/epoberezkin/ajv-errors

# 更多json-Sechema的参数规范和示例:
http://json-schema.org/examples.html

 

入门demo1:

var Ajv = require('ajv');
var ajv = new Ajv({allErrors: true});

var schema = {
  "properties": {
    "foo": { "type": "string" },
    "bar": { "type": "number", "maximum": 3 }
  }
};

var validate = ajv.compile(schema);

test({"foo": "abc", "bar": 2});
test({"foo": 2, "bar": 4});

function test(data) {
  var valid = validate(data);
  if (valid) console.log('Valid!');
  else console.log('Invalid: ' + ajv.errorsText(validate.errors));
}

 

入门demo2,自定义错误信息: 

var Ajv = require('ajv');
var ajv = new Ajv({ allErrors: true, jsonPointers: true });
require('ajv-errors')(ajv /*, {singleError: true} */ );

var schema = {
    "properties": {
        "bar": {
            type: "number",
            minimum: 100,
            errorMessage: {
                type: "请填写数量",
                minimum: "数量不能小于100"
            }
        },

        "foo": {
            type: "string",
            errorMessage: {
                type: "你TM是不是傻逼,要写string类型啊"
            }
        }
    }
};

var validate = ajv.compile(schema);

test({ "foo": 2, "bar": 4 });

function test(data) {
    var valid = validate(data);
    if (valid) console.log('Valid!');
    else console.log(validate.errors);
}

 

posted @ 2017-07-17 09:56  贝尔塔猫  阅读(3120)  评论(0编辑  收藏  举报