敲除验证复选框没有显示消息

时间:2013-08-16 11:02:18

标签: knockout-validation

我有这个jsFiddle http://jsfiddle.net/63qJe/3/,但不显示验证方法。

HTML:

<input type="checkbox" data-bind="checked: approveTerms"/>
<label for="algvw">Yes, I agree to the general terms and conditions</label>
<span data-bind="validationMessage: approveTerms"></span>
<button type="button" data-bind="click: stepForward">Commit order</button>

JS:

ko.validation.rules['checkedTerms'] = {
    validator: function (value) {
        console.log(value);
        if (!value)
            return false;
        return true;
    }
};
function ovm() {
    var self = this;
    self.approveTerms = ko.observable(false).extend({
        checkedTerms: { message: 'Approval required' }
    });
    self.currentStep = ko.observable(1);
    self.stepForward = function () {
        if (self.currentStep() === 1)
            commitOrder(self);
    };
}
window.vm = new ovm();
ko.applyBindings(vm);

function commitOrder(vm) {
    if (vm.approveTerms())
        alert("GO!");
    else
        alert("Nooooooooo");
}

我对KO很新,还在学习。我在textfields上有其他验证器和那些工作,但是这个复选框让我很头疼。

为什么我不能这样做:

self.approveTerms = ko.observable(false).extend({ required: true, message:'approval req.' });

2 个答案:

答案 0 :(得分:4)

如果您要创建custom validator rule,则需要致电

 ko.validation.registerExtenders();

在您的自定义规则之后,为了验证插件注册新的验证器。

演示JSFiddle

或者,如果您只想检查复选框是否已选中,则可以使用built in equal验证码:

self.approveTerms = ko.observable(false).extend(
    { equal: { params: true, message:'approval req.' }});

演示JSFiddle

答案 1 :(得分:1)

尝试使用自定义验证器

var checkedTerms = function (value) {
        alert(value);
        console.log(value);
        if (!value) {
            return false;
        }
        return true;
    };

function ovm() {
    var self = this;
    self.approveTerms = ko.observable(false).extend({
        validation: { validator:checkedTerms, message: 'Approval required' }
    });
    self.currentStep = ko.observable(1);
    self.stepForward = function () {
        if (self.currentStep() === 1)
            commitOrder(self);
    };
}

这是工作小提琴:http://jsfiddle.net/63qJe/5/