1

I have items dispersed within my view that are visible based on dates, drop down selections and the like. I would like to use ko validation because its nice to put validation logic in my model and not have to use a stupid form like you would with jquery validation.

The bonus I am seeing with jquery validation is that it only validates visible items even if they have the required class. Is there anyway to get this functionality from ko validation?

segFault
  • 1,228
  • 2
  • 18
  • 41

1 Answers1

1

In your knockout model I guess you should have a flag for visibility. You can use onlyIf option based on the flag. Something like:

self.IsFieldVisible = ko.observable(true); //Or False
self.FieldToValidate= ko.observable().extend({
  required: {
    onlyIf: function () { 
      return self.IsFieldVisible();
    }
  }
});
estebane97
  • 1,138
  • 2
  • 7
  • 25
  • and what if I need to hide another type of validation messages (for example, checking is it a number or not)? – Dmitriy Kachko Jul 19 '13 at 17:19
  • 1
    You can use `onlyIf` with any validation type, even custom validations. Have a look this [question](http://stackoverflow.com/questions/14601463/conditional-validation-not-working-for-anonymous-knockout-validation-rule) to see how it works with custom validation – estebane97 Jul 22 '13 at 03:56