Knockout Validation length is always 0

这一生的挚爱 提交于 2019-12-25 07:59:40

问题


I am new to using knockout and I am trying to get the validation plug-in to work. However, I tried ViewModel.errors().length == 0 but it is always zero when i check the isValid - I always get true.

Here is the rest of my code, please help.

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:


ko validation group should be attached with this not with the function itself so your code wil be like :-

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);
};

And save function will be:-

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



来源:https://stackoverflow.com/questions/22319513/knockout-validation-length-is-always-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!