2014-03-07 38 views
0

我有这个模型KO验证:model.errors未定义

var MarketResearch = function (data) { 
    var self = this; 
    self.Validate = function() { 
     if (!self.isValid()) { 
      self.errors.showAllMessages(); 
      return false; 
     } 
     return true; 
    }; 
    this.id = data ? data.id : 0; 
    this.city = ko.observable(data ? data.city : '').extend({ required: true }); 
    this.since = ko.observable(data ? data.since : '').extend({ required: true }); 
    this.title = ko.observable(data ? data.title : '').extend({ required: true }); 
} 

这里是视图:

function onDocumentReady() { 

    koValidationConfig() 

    // initializeDataPickers(market); 
    // createCkEditor('market_editor'); 
    ko.applyBindings(market, document.getElementById("market-form")); 
} 
var market = new MarketResearch(null); 
    function onSaveMarketClicked() { 
     market.errors.showAllMessages(); 
    } 

function koValidationConfig() { 
    ko.validation.rules.pattern.message = 'Invalid.'; 

    ko.validation.configure({ 
     // registerExtenders: true, 
     messagesOnModified: true, 
     insertMessages: true, 

     decorateInputElement: true, 

    }); 
    ko.validation.registerExtenders(); 
} 

我有一些必填字段在这里。当我在字段中没有显示任何内容时,它显示“此字段是必需的”并为表单元素着色。 但market.errors始终未定义,所以我无法检查表单是否有效!

market.errors.showAllMessages(); 

不起作用。

Ko.validation被定义,我检查过。

怎么了?

回答

1

ko.validationerrors属性添加到观察对象而不是模型。您还需要使用.extend上的可观察项来启用验证。

+0

model.errors()应该给出一个错误数组 – Euphe

+1

在你的代码中没有什么会提示这个。 – sabof

+0

现在我翻阅了我理解的文档。非常感谢你!我想(因为我的伙伴告诉我),我可以默认做到这一点。 – Euphe