Search code examples
asp.net-mvc-3knockout.jsknockout-validation

validation with onlyIf doesn't work


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


Solution

  • 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.