Clearing or resetting a knockout validation validatedObservable?
Asked Answered
F

2

14

I have a view model as such:

var prop1 = ko.observable().extend{ required: true },
    prop2 = ko.observable().extend{ required: true };

var validation = ko.validatedObservable([prop1, prop2]);

function resetFields() {
    prop1(undefined);
    prop2(undefined);
}

var vm = {
    prop1: prop1,
    prop2: prop2,
    validation: validation,
    reset: resetFields
};

The properties prop1 and prop2 are being validated correctly via the validatedObservable, however when I execute resetFields, these properties then have errors on them since they've been modified and are required.

Is there a way to reset the validated observable, as if it had not been changed?

Update: I was sourcing knockout.validation from NuGet, and using v1.0.1

Fernyak answered 29/7, 2013 at 17:38 Comment(0)
E
18

You cannot reset on the validatedObservable level but you can call clearError on the individual properties:

vm.reset();
console.log(vm.validation.isValid()); // output: false
prop1.clearError();
prop2.clearError();
console.log(vm.validation.isValid()); // output: true

Demo JSFiddle.

Note: It only works with a "recent" version of the validation plugin so the clearError is not included in the CDNJS and Nuget version of plugin. My JSFiddle demo uses the latest version (9fd5a4d2da) from GitHub.

Eras answered 29/7, 2013 at 19:3 Comment(0)
F
12

When using a validated observable, I found out that you can call validatedObservable.errors.showAllMessages(false) after you have cleared the observable, which is behaving the way I was expecting in my application.

Fernyak answered 27/9, 2013 at 7:32 Comment(1)
This solution could work but not in all cases: the showAllMessages(false) only sets the isModied observables to false which results in the error messages removed however it does not clear the validation result. So the isValid() will remain false: vm.reset(); console.log(vm.validation.isValid()); //output: false vm.validation.errors.showAllMessages(false) console.log(vm.validation.isValid()); //output: false jsfiddle.net/CjsCSEras

© 2022 - 2024 — McMap. All rights reserved.