0

I'm using knockout validation to validate a form. Each field has a custom set of rules.

In my application an administrator should have the rights to chose some rules from a predefined set of rules for a specific field. I will have button for each input field that will open a modal where all the rules will be displayed is a check box and the administrator should be able to chose from them an define custom params or messages.

My question is: How can I define the rules and then pass them to ko.observable.extend(rules) so I could change the ones that I validate against in the application view.

I tried sending them as a string but no success:

var lastNameRules = '{ minLength: 2, required: true }';
var lastName = ko.observable().extend(lastNameRules);
Razvan
  • 3,017
  • 1
  • 26
  • 35

1 Answers1

0

I managed to get it working, so I'm posting the solution. I am declaring the rules in an array as structures and then I apply each rule to the observable:

var rules = [{ required: true }, { minLength: 3 }, { maxLength: 10 }];

    for (var i = 0; i < rules.length; i++) {
        lastName.extend(rules[i]);
    }

This way all the rules are implemented.

Edit: Other way would be to push some rules into the rules array of the observable:

lastName.rules().push({ rule: "email", params: true });

This way the extend has to be declared before adding the rules, because of the additional functionality that is added to the observable. Otherwise there will be no rules array as a field in the observable.

Razvan
  • 3,017
  • 1
  • 26
  • 35