I am trying to use the Knockoutjs Validation add on from GitHub. Most of it seems to work just fine but when I try to use the extended validation mustEqual(password/confirm password) it does not seem to do anything. What am I missing?
I would very much like to learn this extender technique for future use.
(also this whole html and javascript get loaded to the page via AJAX call. if that has anything to do with it.)
My javascript
function UserAccount(data) {
var self = this;
self.Password = ko.observable(data.Password).extend({ required: true, minlength: 6, message: "Password is required", maxLength: 12 });
self.Firstname = ko.observable(data.Firstname).extend({ required: true, minlength: 6, message: "Firstname is required", maxLength: 40 });
self.Lastname = ko.observable(data.Lastname).extend({ required: true, minlength: 6, message: "Lastname is required", maxLength: 40 });
self.Email = ko.observable(data.Email).extend({ required: true, minlength: 6, message: "Email is required", email: true, maxLength: 90 });
self.ConfirmPassword = ko.observable().extend({ mustEqual: self.Password()});
...........................Other Code............
}
ko.validation.rules['mustEqual'] = {
validator: function (val, otherVal) {
alert("Hello");
return val === otherVal;
},
message: 'The field must equal {0}'
};
$(document).ready(function () {
ko.applyBindings(new UserAccount(initdata), $("#UserAccount").get(0));
ko.validation.registerExtenders();
});
Your custom validator code is OK. But you are not calling correctly the
ko.validation.registerExtenders();
method.Although it is not explicitly stated but you need to call
ko.validation.registerExtenders();
before you are callingko.applyBindings
.So to fix your code you just need to write:
But you will face another problem: the
mustEqual
validator is for comparing to static values so it won't work if you want to compare two properties like password with confirm password.What you need is something like the user contributed "Are Same" validator:
What you can use like:
Demo JSFiddle.