Search code examples
knockout.jsknockout-validation

how to add knockout validation to a previously not required field


I have a simple knockout viewmodel with an array of passengers in it. Each passenger has, firstname, lastname and number properties. The number field for each passenger is not mandatory unless they tick a checkout on the root of the model. I'm not sure how to then enforce validation on the number textbox when the user has opted to include the number textbox? Hope that's clear, my progress is available in the jsfiddle below. Thanks!

Code attempt

self.number = ko.observable(false).extend('not sure how to ');

http://jsfiddle.net/Cf8Ap/3/

UPDATE

Have tried the following. This attempt is looking at the toggle() value to know whether the number textbox is required - although not successfully..

http://jsfiddle.net/Cf8Ap/4/

The update includes the following change

var Passenger = function() {
  self.cardNumber = ko.observable().extend({required: {onlyIf: function() {
        return $parent.toggle() === 'true';

Solution

  • $parent etc is a view only feature, anyway, there are alot of errors in your code here is a working version¨

    http://jsfiddle.net/Cf8Ap/7/

    self.cardNumber = ko.observable().extend({
        required: {
            message: 'number is required',
            onlyIf: function() {
                return self.showCardNumber();
            }
        }
    });