这是验证两个输入字段 firstname
和 lastname
的示例,both
这两个字段都是必需的
查看
<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>
View 模型
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
.error
{
background-color: #f5f5f5;
}
我尝试在 JSFiddle 中运行这段代码.但它不起作用,即使初始值也未显示在输入字段 FirstName
和 LastName
中。我无法找出错误。
最佳答案
您包括了 knockout 文库吗?它似乎对我有用。 https://jsfiddle.net/co2y5x60/
https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js
关于javascript - knockoutJS 中的验证码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39992572/