我正在使用“相等”验证规则。
self.FirstName = ko.observable();
self.Lastname = ko.observable();
self.ValidationMessage = ko.computed(function(){
return 'This is my dynamic validation message. ' + self.FirstName() + ' ' + self.LastName()
});
self.MyComputed = ko.computed(function() {
// Keep it simple for example purpose
return true;
}).extend({ equal: { message: self.ValidationMessage, params: false } });
我想知道是否有任何方法可以根据计算值或其他可观察值使验证消息动态化。
答案 0 :(得分:4)
你不需要self.ValidationMessage
。而是使用function
作为消息,它将被动态调用。
function vm() {
var self = this;
self.FirstName = ko.observable();
self.LastName = ko.observable().extend({
equal: {
message: function(params, observable) {
return 'First Name: ' + params + ' and Last Name: ' + observable() + ' are not the same.';
},
params: self.FirstName
}
});
}
ko.applyBindings(new vm());
.validationMessage { display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script>
<input data-bind="textInput: FirstName"><input data-bind="textInput: LastName">