Knockout Validation validatedObservable group erro

2019-08-03 21:41发布

I have a group of items that I need to validate as a whole. I setup a validatedObservable on the group, but the error message doesn't display.

I have a simplified example here. I want each number to be between 0-100 and the sum to be exactly 100. How do I handle this kind of validation?

Update: I know in this example I could just make a ko.computed and validate that, but that's not what I need.

Example: http://jsfiddle.net/CGuW2/5/

0-100:<input data-bind="value: num1, valueUpdate: 'afterkeydown'"/><br>
0-100:<input data-bind="value: num2, valueUpdate: 'afterkeydown'"/><br>
<span class="validationMessage" data-bind='text: isValidSum.errors()'></span>

ko.validation.rules['mustEqual'] = {
    validator: function (val, otherVal) {
        return (parseInt(val.num1()) + parseInt(val.num2())) == otherVal;
    },
    message: 'total must equal {0}'
};
ko.validation.registerExtenders();

var viewModel = {
    num1: ko.observable("50").extend({ number: true, min: 0, max: 100 }),
    num2: ko.observable("50").extend({ number: true, min: 0, max: 100 })
};

viewModel.isValidSum = ko.validatedObservable({
                            num1: viewModel.num1,
                            num2: viewModel.num2
                        }).extend({ mustEqual: 100 });

ko.applyBindings(viewModel);

2条回答
做个烂人
2楼-- · 2019-08-03 22:01

Check this fiddle, I've implemented sum validation.
http://jsfiddle.net/CGuW2/3/
I think the problem was that you can not use extend on validatedObservable

查看更多
欢心
3楼-- · 2019-08-03 22:16

I needed to bind on text: isValidSum.error instead of text: isValidSum.errors(). Also, it looks like you have to bind visible: !isValidSum.isValid() when you do this.

So my solution looks like this:

Example: http://jsfiddle.net/CGuW2/6/

0-100:<input data-bind="value: num1, valueUpdate: 'afterkeydown'"/><br>
0-100:<input data-bind="value: num2, valueUpdate: 'afterkeydown'"/><br>
<span class="validationMessage" data-bind='visible: !isValidSum.isValid(), text: isValidSum.error'></span>
查看更多
登录 后发表回答