Knockout checking for isSame or mustMatch examples

I am trying to use the Knockoutjs validation add-on from GitHub. Most of them seem to work fine, but when I try to use the advanced mustEqual check (password / password confirmation), it does nothing. What am I missing?

I would very much like to learn this expander method for future use.

(Also, all this html and javascript are loaded onto the page via an AJAX call if this 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(); }); 
+7
javascript jquery
source share
1 answer

Your custom verification code is OK. But you are not correctly calling the ko.validation.registerExtenders(); method ko.validation.registerExtenders(); .

Although this is not explicitly stated, you need to call ko.validation.registerExtenders(); before , you call ko.applyBindings .

So, to fix your code, you just need to write:

 $(document).ready(function () { ko.validation.registerExtenders(); ko.applyBindings(new UserAccount(initdata), $("#UserAccount").get(0)); }); 

But you will encounter another problem: the mustEqual validator mustEqual designed to compare with static values, so it will not work if you want to compare two properties, such as password with password confirmation.

What you need is something like the user who contributed the β€œSame” validator :

 ko.validation.rules['areSame'] = { getValue: function (o) { return (typeof o === 'function' ? o() : o); }, validator: function (val, otherField) { return val === this.getValue(otherField); }, message: 'The fields must have the same value' }; 

What you can use, for example:

 self.Password = ko.observable(data.Password).extend({ required: true, minlength: 6, message: "Password is required", maxLength: 12 }); self.ConfirmPassword = ko.observable().extend({ areSame: self.Password }); 

JSFiddle demo.

+10
source share

All Articles