问题
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