Chitika

February 4, 2013

Knockout validation: Сomparison of the two fields

I would like to share how I've solved this problem.

The typical example is a simple registration form with the view model:

    var viewModel = ko.validatedObservable({
        userName: ko.observable().extend({ required: true }),
        password: ko.observable().extend({ required: true }),
        passwordConfirm: ko.observable().extend({ required: true })
    });

Then you can easily check is your viewModel valid using:

    viewModel.isValid();

And it works very good. But you don't have validation are your password and password confirmation fields equal.

To do it you have to add these lines:

    viewModel().password.extend({ equal: viewModel().passwordConfirm });
    viewModel().passwordConfirm.extend({ equal: viewModel().password });

After that you will have client notification as well as ability to check is your view model valid in code (as mentioned above).

That's all.
Good luck.