0
這與我的另一個問題here有關! 我想在不使用驗證庫的情況下創建自定義驗證擴展器。淘汰賽無法使用擴展程序擴展多個觀察值
我無法將我的擴展器擴展到多個可觀察值。在下面的情況下,擴展器應用於密碼字段,但不適用於重新輸入密碼字段。
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script type="text/javascript" src="knockout-3.4.0.js"></script>
Name:<input type="text" data-bind="value:Name" /><br />
Already A User: <input type="checkbox" data-bind="checked:AlreadyUser" /><br />
Password:<input type="password" data-bind="value:Password,visible:PasswordVisible" /><br />
Retype Password:<input type="password" data-bind="value:RetypePassword,visible:PasswordVisible" /><br />
<input type="button" value="Submit" onclick="validateModel();" />
<script type="text/javascript" >
var pageModel;
ko.extenders.Validate = function (target, validateOptions) {
target.HasErrors = ko.computed(function() {
var newValue = target();
var required = validateOptions.required();
var validationType = validateOptions.validationType;
if (ko.unwrap(required)) {
switch (validationType) {
case "Text":
return newValue == '';
default:
target.HasErrors(false);
break;
}
}
return false;
}, null, { deferEvaluation: true }).extend({ notify: 'always' });
return target;
};
//The model itself
var ViewModel = function() {
var self = this;
self.Name = ko.observable('');
self.AlreadyUser = ko.observable(false);
//computed variable that sets the visibility of the password field. I have to clear the password when am making it invisible
self.PasswordVisible = ko.computed(function() { return !this.AlreadyUser(); }, this).extend({ notify: 'always' });
//this field is only required when visible
self.Password = ko.observable('').extend({ Validate: { required: function() { return self.PasswordVisible(); }, validationType: "Text" } });
self.RetypePassword = ko.observable('').extend({ Validate: { required: function() { return self.PasswordVisible(); }, validationType: "Text" } });
self.AlreadyUser.subscribe(function (newVal) { self.RetypePassword(''); });
self.HasErrors = ko.computed(function() { return self.Password.HasErrors() && self.RetypePassword.HasErrors(); }, self);
};
//The method calls on click of button
function validateModel() {
alert(pageModel.HasErrors());
}
//create new instance of model and bind to the page
window.onload = function() {
pageModel = new ViewModel();
ko.applyBindings(pageModel);
};
</script>
</body>
</html>
我已經成功地解決了這個問題 – Ramki