Knockout-Validation icon indicating copy to clipboard operation
Knockout-Validation copied to clipboard

Keep invalid values out of the viewmodel

Open bradstiff opened this issue 8 years ago • 1 comments

My viewmodels have a bunch of numeric values, and some summary calculations based on the numeric values. I am using the appropriate numeric validation rules. Problem is, if the user enters non-numeric data, it gets into my viewmodel with undesirable impact on my calculations.

I would like to propose that the "validatable" extender be changed so that it wraps the model's observable with a pure computed. By doing this, it could intercept invalid entries and not allow them to be written to the model.

bradstiff avatar Feb 15 '16 17:02 bradstiff

I've taken a stab at this but quickly ran into a problem. Here's a simple interceptor, based on the Knockout documentation:

function extender(target: KnockoutObservable<any>): KnockoutObservable<any> {
    var interceptor = ko.pureComputed<any>({
        read: target,
        write: (newValue?: any) => {
            target(newValue);
        }
    }).extend({ notify: 'always' });

    interceptor(target());

    console.log("dumping interceptor");
    console.dir(interceptor);
    console.log("dumping target");
    console.dir(target);

    return interceptor;
}

When further extending the observable with validation rules, they will be added to the interceptor. Since reading the the interceptor still returns the original value, you cannot easily execute the validation on the newValue being written.

Perhaps I'm taking a wrong approach at this. I'm thinking the example from the Knockout documentation is too simple, and instead of simply returning the underlying observable in read, it might be necessary to keep an internal value and subscribe to the underlying observable to keep values in sync.

stijnherreman avatar Jun 29 '16 15:06 stijnherreman