Search code examples
knockout.jsknockout-validation

Knockout partial validation of viewmodel


I am rather new to KockoutJS But I have this working jsFiddle which validates. But I would like to have a set of about 5 observables and validate that set. It is meant as some sort of wizard and at each step a validation of the observables in that step.

I have read about validatedObservable but do I have to make a var for it outside the viewModel and then reference the observables in the viewmodel? I found this as only reference and having difficulties understanding the grouping and validating with knockout validation.

Here is my JS code:

function ovm() {
    var self = this;
    this.delStreet = ko.observable("").extend( {required: true} );
    this.deliveryNotSameAsInvoice = ko.observable(false);
    this.invStreet = ko.observable('');
    this.delCountry = ko.observable("");
    var invStreetCheck = ko.computed(function(){
        var checked = self.deliveryNotSameAsInvoice(),
            delStreet = self.delStreet();
        if(!checked)
            return self.invStreet(delStreet);
        return self.invStreet();
    });
}

var vm = new ovm();
ko.applyBindings(vm);

$("#s1").click(function(){
    alert(vm.delStreet.isValid());
});

Solution

  • Here's how I solved this problem for someone else.

    It uses ValidatedViewModel from Carl Schroed and allows you to choose which validation options you want to apply - extremely handy for multi-step forms.