自定义淘汰赛验证2次下拉菜单

时间:2014-08-13 16:33:34

标签: knockout.js knockout-validation

如何使用敲除验证编写自定义规则,以便两个下拉菜单触发相同的错误消息?下拉默认值为-1,如下所示,但我很难让错误信息同时适用于两者。当值为-1时,错误消息正确显示第一个下拉列表(self.select1),但我也无法在第二个下拉列表中使用它(self.select2)

查看模型

self.select1 = ko.observable('-1');
self.select2 = ko.observable('-1');

标记

<div data-bind="css: { valid: (select1.isModified() && select1.isValid()), requiredText: (select1.isModified() && !select1.isValid())}">
    <select data-bind="options: xxx1, optionsText: 'value', optionsValue: 'name', value: select1, event:{blur: function(){select1.isModified(true);}}"></select>
</div>    

<div data-bind="css: { valid: (select2.isModified() && select2.isValid()), requiredText: (select2.isModified() && !select2.isValid())}">
    <select data-bind="options: xxx2, optionsText: 'value', optionsValue: 'name', value: select2, event:{blur: function(){select2.isModified(true);}}"></select>
</div>    

错误消息

<div class="LV_validation_message_wrapper">
    <span role="alert" class="LV_validation_message " data-bind="if: select1.isModified() && !select1.isValid(),
                style: { display: select1.isModified() && !select1.isValid() ?'block':'none' }, 
                attr: { title: select1.error }, validationMessage: select1" title="error message" style="display: block;">error message</span>
</div>

1 个答案:

答案 0 :(得分:0)

你可以通过一个易读且易于理解的简单方法来研究这个问题

见工作Fiddle

示例视图模型:

function ViewModel() {
    var self = this;
    self.choiceval =ko.observable("");
    self.numberval =ko.observable("");
    var choices = [
        { id: 1, name: "one" },
        { id: 2, name: "two" },
        { id: 3, name: "three" }
    ];
     var numbers = [
        { id: 1, name: "one" },
        { id: 2, name: "two" },
        { id: 3, name: "three" }
    ];

    self.choices = ko.observableArray(choices);
    self.numbers = ko.observableArray(numbers);



    self.Validation = ko.validatedObservable([
        self.numberval.extend({ required: true }),
         self.choiceval.extend({ required: true })

    ]);


}
ko.applyBindings(new ViewModel());