这是两个输入字段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>
视图模型
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
中。我无法弄清楚错误。
答案 0 :(得分:2)
你是否包括淘汰图书馆?它似乎对我有用。 https://jsfiddle.net/co2y5x60/
https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js