zoukankan      html  css  js  c++  java
  • 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);
    }
  • 相关阅读:
    SQLSTATE[HY000] [2002] No such file or directory(转)
    pg_stat_activity各字段的含义
    DedeCMS 后台空白问题
    关于XP和win7 的IIS发布问题
    500错误
    swfupload上传多张照片出现404 错误?(已解决)
    url字符串编码乱码问题
    遮罩层《一》
    Java集合按照索引分页,以及JS数组代码按照索引分页的源码
    填充整个页面
  • 原文地址:https://www.cnblogs.com/CyLee/p/7192941.html
Copyright © 2011-2022 走看看