我面临使用淘汰赛验证单选按钮的问题。
这是显示我的问题的小提琴 - fiddle。
<input type="radio" data-bind="checked:agree" name="agree" />agree
<br />
<input type="radio" data-bind="checked:agree" name="agree" />disagree
<br />
<input type="checkbox" data-bind="checked:vehicle" value="bike" />bike
<br />
<input type="checkbox" data-bind="checked:vehicle" value="car" />car
<br />
agree: ko.observable().extend({
required: true
}),
vehicle: ko.observable().extend({
required: true
}),
save: function () {
if (this.isValid()) {
alert('success');
}
else {
this.errors.showAllMessages();
alert('error');
}
}
答案 0 :(得分:3)
你的电台需要一个值:
<input type="radio" data-bind="checked:agree" name="agree" value="1" />agree
<input type="radio" data-bind="checked:agree" name="agree" value="2" />disagree
对于消息,当您的observable未使用validationMessage
绑定绑定时(此处使用value
绑定),您需要使用checked
绑定:
<span data-bind="validationMessage: agree"></span>
修改强>
如果您需要强制用户选中该复选框,则需要创建自己的规则:
ko.validation.rules['trueOnly'] = {
validator: function(val) {
return val;
},
message: "This checkbox is required"
}
ko.validation.registerExtenders();
然后像这样延伸:
vehicle: ko.observable().extend({
trueOnly: true
}),
查看here
要检查是否至少有一个是真的,您需要进行一些更改:
验证规则可能如下所示:
ko.validation.rules['oneOrMoreChecked'] = {
validator: function (val, params) {
return val || params.otherVal();
},
message: "This checkbox is required"
}
验证声明:
vm().vehicle.extend({
oneOrMoreChecked: {
otherVal: vm().vehicle2
}
});
更新fiddle