Search code examples
knockout.jsknockout-validation

How to enumerate rules from a validated viewmodel property (using knockout.validation)


If I have a simple view model, with a validated property, e.g:

var viewModel = {
    myProperty: ko.observable().extend({ 
        email: true,
        required: true
    })
};

and a component that expects such a property:

<myComponent data-bind="params: { validatedProperty: myProperty }"></myComponent>

how can I determine which validation rules have been defined for myProperty from within the component code? i.e.

var ComponentViewModel = function(params) {
    // DOESN'T WORK: rules is always empty
    var firstRule = params.validatedProperty.rules[0];
};
return { viewModel: ComponentViewModel, template: htmlString};

Solution

  • rules is an observable. Invoke it to get its contents:

    var firstRule = params.validatedProperty.rules()[0];