如何验证可观察对象是否具有所有必需成员?

时间:2014-06-02 22:26:17

标签: javascript json knockout.js validation jsonschema

基本上我想在应用绑定之前验证我的observable,这样我就永远不会得到没有定义错误的东西。

假设我有一个javascript类,它定义了我需要的所有内容,并且我想验证从ajax创建的observable。

有通用的方法吗?

修改

http://jsfiddle.net/rgneko/GuR8v/

目前演示会抛出错误,因为其中一个项目没有id属性。我想验证所有项目是否有效。

$(document).ready(function () {
    function ModelToTestAgainst(id, name, type, items) {
        this.id = id;
        this.name = name;
        this.type = type;
        this.items = items;
    }
    var data = {
        items: [{
            id: 1,
            name: 'name1',
            type: 'folder',
            items: []
        }, {
            id: 2,
            name: 'name2',
            type: 'file',
            items: []
        }, {
            name: 'name2',
            type: 'file',
            items: []
        }]
    };
    var someRandomObservaleIGotFromWherever = ko.mapping.fromJS(data);
    // I want to Validate(someRandomObservaleIGotFromWherever) before apply bindings

    ko.applyBindings(someRandomObservaleIGotFromWherever);
});

3 个答案:

答案 0 :(得分:0)

为什么不将它映射/包装到您知道具有所需属性的视图模型中?

function ViewModel(model) {
    this.x = ko.observable(model.x || 0);
    this.y = ko.observable(model.y || 0);
}
var original = { x: 27 }; // Use your ajax object here.
var viewModel = new ViewModel(original);

答案 1 :(得分:0)

如何使用JSON Schema验证。

我使用了来自Tiny Validator的库来启用验证。验证很容易添加为可观察的扩展

$(document).ready(function () {
    // Attach a validationSchema method to all observable types
    ko.subscribable.fn["validateSchema"] = function(schema){
        // Convert the observable back to an object literal to test.
        var source = ko.mapping.toJS(this());

        return tv4.validate(source, schema);
    };

    // Define schema for ModelToTestAgainst
    var modelSchema = {
        "$schema": "http://tempuri.org/ModelToTestAgainst",
        "title": "ModelToTestAgainst Set",
        "type": "array",
        "items": {
            "title": "ModelToTestAgainst",
            "type": "object",
            "properties" : {
                "id" : { 
                    "type": "number", 
                    "minimum" : 1
                },
                "name" : { "type": "string" },
                "type" : { "type": "string" },
                "items" : { "type" : "array" }
            },
            "required": ["id", "name", "type", "items"]
        }
    };
    function ModelToTestAgainst(id, name, type, items) {
        this.id = id;
        this.name = name;
        this.type = type;
        this.items = items;
    }
    var data = {
        items: [{
            id: 1,
            name: 'name1',
            type: 'folder',
            items: []
        }, {
            id: 2,
            name: 'name2',
            type: 'file',
            items: []
        }, {
            name: 'name2',
            type: 'file',
            items: []
        }]
    };
    var obs = ko.mapping.fromJS(data));
    var isValid = obs.items.validateSchema(modelSchema);

    if( isValid ) {        
        ko.applyBindings(obs);
    }
});

答案 2 :(得分:0)

有一个标准的JSON模式,在http://json-schema.org/中定义。

架构可以简单如下:

var schema = {"type" : "object"};

需要将值作为对象。或者更复杂,比如json-schema.org上的这个例子:

{
  "title": "Example Schema",
  "type": "object",
  "properties": {
    "firstName": {
      "type": "string"
    },
    "lastName": {
      "type": "string"
    },
    "age": {
      "description": "Age in years",
      "type": "integer",
      "minimum": 0
    }
  },
  "required": ["firstName", "lastName"]
}

需要存在多个属性,定义它们的类型,甚至是其中一个属性的最小值。

然后你需要一个允许用这种模式验证JS对象的库。在同一网站中,您可以找到a list of libraries for validating (and parsing, creating documentation...)。请注意,并非所有库都已更新,并且并非所有库都支持最新的JSON模式版本。

例如,using JSV,您可以像这样进行验证:

var report = env.validate(json, schema);