2

I am running into issue when trying to do :

newNoteText: ko.observable().extend({ required: { onlyIf: function () { return this.ShowNote == true } } })

I noticed that this doesn’t work, but when I put the code back like this, it works fine:

newNoteText: ko.observable().extend({ required: true })

http://sdrv.ms/WJC3fS

https://skydrive.live.com/redir?resid=33048714B5BF3B4B!2027

jmogera
  • 1,689
  • 3
  • 30
  • 65

2 Answers2

4

The proper syntax to use the onlyIf option on a rule is :

newNoteText: ko.observable().extend({ 
  required: {
    onlyIf: function(){
      return someFlagIsTrue;
    }
  }

Cf. this answer to one of your previous questions (by Eric Barnard, main contributor to Knockout Validation).


Regarding, your code, apart from Knockout Validation's syntax, there are two other things to worry about :

  1. return something == true is the same as return something (not mentioning JavaScript's way of handling == and === operators, see more about this here).

  2. In your function the value of this isn't what you seem to think it is (here it refers to the parameter between the parenthesis of extend()).

If you want to access the value of one of the other observables of your view model, you should be doing something like :

newNoteText: ko.observable().extend({ 
  required: {
    onlyIf: function(){
      return self.ShowNote();
    }
  }

Where self is defined at the top of your view model constructor, like var self = this;. See more about this pattern here.

Community
  • 1
  • 1
Thibaud Colas
  • 1,248
  • 1
  • 16
  • 24
  • tried it with param didn't work. I will try to create an example. – jmogera Feb 27 '13 at 05:05
  • here is example. I create the test project exactly as I have it my project: https://skydrive.live.com/redir?resid=33048714B5BF3B4B!2027 – jmogera Mar 01 '13 at 14:01
0

The params option mentioned by ThibWeb isn't needed - knockout.validation.js sets this by default to true in the addExtender method:

if (params.message || params.onlyIf) { 
  return ko.validation.addRule(observable, {
    rule: ruleName,
    message: params.message,
    params: utils.isEmptyVal(params.params) ? true : params.params,
    condition: params.onlyIf
 });

The Eric Barnard answer was in 2011, presumably before this was defaulted to true.

However, if your code sets any validation defaults, you might be writing an HTML5 required attribute into the HTML, or reading one that is set in the HTML:

ko.validation.configure({
    parseInputAttributes: true, //default is false
    writeInputAttributes: true //default is false
});

I've found this causes an onlyIf required condition to be effectively ignored, since you are adding an extra required rule which is always applied.

Appetere
  • 6,003
  • 7
  • 35
  • 46