在按钮上调用Knockout验证扩展器单击

时间:2016-08-08 15:11:04

标签: javascript validation knockout.js

我一直在阅读许多问题,询问如何在按钮点击事件中调用敲除验证扩展程序。但所有接近回答问题的答案都涉及使用knockout-validate库的变通方法。我没有使用敲除验证库。我想要做的就是使用敲除扩展器中定义的验证规则验证按钮单击事件上的输入字段。

为简单起见,我将使用knockout documentation中所需的扩展程序并将其应用于一个简单的用例。此用例接受输入,按钮单击事件使用用户输入的值执行某些操作。或者,如果未输入任何值,则更新视图以显示验证消息。

淘汰赛代码:

ko.extenders.required = function (target, overrideMessage) {
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    function validate(value) {
        target.hasError(value ? false : true);
        target.validationMessage(value ? "" : overrideMessage || 'Value required');
    }

    return target;
};

function MyViewModel() {
    self = this;
    self.userInput = ko.observable().extend({ required: 'Please enter a value' });

    /**
     * Event handler for the button click event
     */
    self.processInput = function () {
        //Validate input field
        //How to call the validate function in the required extender?

        //If passes validation, do something with the input value
        doSomething(self.userInput());
    };
}

标记:

<input type="text" data-bind="value: userInput, valueUpdate: 'afterkeydown'" />
<span data-bind="visible: userInput .hasError, text: userInput .validationMessage" class="text-red"></span>
<button data-bind="click: processInput ">Do Something</button>

如何触发按钮点击事件的验证并显示验证消息(如果它没有通过验证?)

1 个答案:

答案 0 :(得分:1)

我相信你在看这里的例子 - http://knockoutjs.com/documentation/extenders.html

你不能直接调用validate,但是subscribe会监视值并在更改时运行validate函数并更新你可以检查的observable - hasError。

ko.extenders.required = function (target, overrideMessage) {
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    function validate(value) {
        target.hasError(value ? false : true);
        target.validationMessage(value ? "" : overrideMessage || 'Value required');
    }
    
    //initial validation
    validate(target());
 
    //validate whenever the value changes
    target.subscribe(validate);
 
    //return the original observable
    return target;
};

function MyViewModel() {
    self = this;
    self.userInput = ko.observable().extend({ required: 'Please enter a value' });

    /**
     * Event handler for the button click event
     */
    self.processInput = function () {
        if(self.userInput.hasError()){
          console.log('has error');
        }else{
          console.log('no error');
        }
    };
}

// Activates knockout.js
ko.applyBindings(new MyViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="text" data-bind="value: userInput, valueUpdate: 'afterkeydown'" />
<span data-bind="visible: userInput .hasError, text: userInput .validationMessage" class="text-red"></span>
<button data-bind="click: processInput ">Do Something</button>