Knockout验证长度始终为0

时间:2014-03-11 07:56:08

标签: javascript knockout.js durandal

我是使用knockout的新手,我正在努力让验证插件工作。但是,我尝试了ViewModel.errors()。length == 0但它始终为零 当我检查isValid时 - 我总是成真。

以下是我的其余代码,请帮忙。

define(['knockout','knockout-validation', 'services/changeup', 'services/currencies', 'plugins/router'], function (ko, validation, changeup, currencies, router) {

ko.validation.configure({
    insertMessages: true,
    decorateElement: true,
    errorElementClass: 'error',
    errorMessageClass: 'help-inline '
});

var ctor = function () {

    this.amount = ko.observable().extend({ required: true, number: true});
    this.currency = ko.observable().extend({ required: true});
    this.requestedAmount = ko.observable();
    this.requestedCurrency = ko.observable().extend({ required: true, notEqual: this.currency, message: 'please'});
    this.comment = ko.observable().extend({ required: true, minLength: 3});
    this.currencies = currencies;
};
ctor.errors = ko.validation.group(ctor);

ctor.prototype.activate = function (activationData) {
};

ctor.prototype.save = function () {


    var valid = ctor.isValid();
    console.log(valid);

    if (ctor.isValid()){
        ctor.errors.showAllMessages();
    }
    else {
        var dto = ko.toJS(this);
        delete dto.currencies;
        changeup.createRequest(dto).then(function(request){
            console.log(request, 'a');
            router.navigate('dashboard');
        });
    }
};

ctor.prototype.cancel = function (activationData) {
};

return ctor;

});

1 个答案:

答案 0 :(得分:1)

ko验证组应附加此功能,而不是功能本身,因此您的代码将如下: -

var ctor = function () {

 this.amount = ko.observable().extend({ required: true, number: true});
 this.currency = ko.observable().extend({ required: true});
 this.requestedAmount = ko.observable();
 this.requestedCurrency = ko.observable().extend({ required: true, notEqual:  this.currency, message: 'please'});
 this.comment = ko.observable().extend({ required: true, minLength: 3});
 // this.currencies = currencies;
 this.errors = ko.validation.group(this);
};

保存功能将是: -

ctor.prototype.save = function () {
 var valid = this.isValid();
 console.log(valid);

 if (!this.isValid()){  //use this 
    this.errors.showAllMessages();
 }
 else {
    var dto = ko.toJS(this);
    delete dto.currencies;
    changeup.createRequest(dto).then(function(request){
        console.log(request, 'a');
        router.navigate('dashboard');
    });
 }
};

Fiddle Demo