简体   繁体   English

KnockoutJS中的验证代码不起作用

[英]Validation code in knockoutJS not working

This is an example of validation for two input fields, firstname and lastname that both the fields are required 这是为两个输入字段验证的例子, firstnamelastnameboth都需要的字段

View 视图

<p data-bind="css: { error: firstName.hasError }">
    FirstName :<input data-bind='value: firstName, valueUpdate: "afterkeydown"' required />
    <span data-bind='visible: firstName.hasError, text: firstName.validationMessage' > </span>
</p>
<p data-bind="css: { error: lastName.hasError }">
    LastName : <input data-bind='value: lastName, valueUpdate: "afterkeydown"' required/>
    <span data-bind='visible: lastName.hasError, text: lastName.validationMessage'> </span>
</p>

ViewModel 视图模型

ko.extenders.required = function(target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    //define a function to do validation
    function validate(newValue) {
       target.hasError(newValue ? false : true);
       target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
    }

    //initial validation
    validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};


function AppViewModel(first, last) {
    this.firstName = ko.observable(first).extend({ required: "Please enter a first name" });
    this.lastName = ko.observable(last).extend({ required: "" });
}

ko.applyBindings(new AppViewModel("Bob","Smith"));

Css 的CSS

.error
{
  background-color: #f5f5f5; 
}

I tried running this code in JSFiddle . 我尝试在JSFiddle中运行此代码。 But its not working, even the initial values are not shown in the input fields, FirstName and LastName .I'm not able to figure out the error. 但是它不起作用,即使初始值也没有显示在FirstNameLastName输入字段中。我无法找出错误。

Were you including the knockout library? 您是否包括淘汰赛库? it seems to work for me. 它似乎为我工作。 https://jsfiddle.net/co2y5x60/ https://jsfiddle.net/co2y5x60/

https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM