我有一个使用knockout加载的下拉列表,我使用了subscribe事件来处理下拉值的更改。然后在更改时,我想动态地向DOM添加一些元素,同时根据条件为文本框添加所需的验证。
以下是HTML,
<div data-bind="foreach: Properties">
<div class="control-group">
<label class="control-label">
<span class="required" data-bind="visible: IsRequired">*</span>
<span data-bind="text: Property"></span>
</label>
<div class="controls">
<input type="text" data-bind="value: PropertyValue" />
<span class="validationMessage" data-bind="validationMessage: PropertyValue"></span>
</div>
</div>
</div>
和subscribe方法,(ccVM:我的视图模型)
ccVM.LevelId.subscribe(function (newValue) {
if (newValue != null) {
/*find relevent subitems from an existing observable array*/
var los = $.grep(ccVM.LevelOfStudies(), function (d) {
return d.LevelId() == newValue;
});
/*clearing existing dynamic array to be populated*/
ccVM.Properties([]);
/*add properties to observable array that matched to selected drop down item*/
if (los.length > 0)
$.each(los[0].LevelOfStudyProperties(), function (i, prop) {
ccVM.Properties.push(new Property({
PropertyId: prop.PropertyId(),
Property: prop.Property(),
IsRequired: prop.IsRequired(),
PropertyValue: prop.PropertyValue()
}));
});
}
});
下面是我如何生成Property对象,
function Property(data) {
this.PropertyId = ko.observable(data.PropertyId);
this.Property = ko.observable(data.Property);
this.IsRequired = ko.observable(data.IsRequired/*boolean*/);
/*required validation is not working*/
this.PropertyValue = ko.observable(data.PropertyValue).extend({ required: data.IsRequired/*boolean*/ });
}
虽然为动态内容添加的验证不起作用,但验证的其余部分正在页面上进行。
有人知道如何使用敲除验证插件来解决这个问题吗?
答案 0 :(得分:1)
您应该使用onlyIf
参数来使验证成为条件。另外,请确保它指向this.IsRequired
可观察对象。
this.PropertyValue = ko.observable(data.PropertyValue).extend({ required: {onlyIf: this.IsRequired }});