Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate checkbox in knockout

I am using knockout.js and knockout.validation plugins. I am trying to validation the checkbox, if it is checked than its valid otherwise invalid. SO for this i created a custom valdation attribute in knockout :

Example Fiddle

ko.validation.rule['checked'] = {
    validator: function (value) {
        if (!value) {
            return false;
        }
        return true;
    }
};

And my view model is :

function VM()
{
    var self = this;
    self.Approve = ko.observable(false).extend({
        checked: { message: 'Approval required' }
    });
    self.Errors = ko.validation.group(self);
    self.Validate = function(){
        if(self.Errors().length > 0)
        self.Errors.showAllMessages();
    };
}

But the validation is not working. Can anybody tell me what i am doing wrong here?

like image 301
Gaurav Avatar asked Feb 19 '13 05:02

Gaurav


1 Answers

There are a few problems with your current approach:

  1. You have miss typed the ko.validation.rule it should be ko.validation.rules
  2. The custom rule definition and the calling of the ko.validation.registerExtenders(); should be done before you first try to use the custom validator.
  3. In order the validation displayed you need to bind it somewhere with validationMessage binding:

    <span data-bind='validationMessage: Approve'></span>
    

So the fixed script:

ko.validation.rules['checked'] = {
    validator: function (value) {
      console.log(value);
        if (!value) {
            return false;
        }
        return true;
    }
};

ko.validation.registerExtenders();

function VM()
{
  var self = this;  
  self.Approve = ko.observable(false).extend({
    checked: { message: 'Approval required' }
  });

  self.Errors = ko.validation.group(self);

  self.Validate = function(){    
     if(self.Errors().length > 0)
       self.Errors.showAllMessages();
  };
}

ko.applyBindings(new VM());

And the HTML:

<input type="checkbox" data-bind="checked: Approve" />  
<span data-bind='validationMessage: Approve'></span>
<button type="button" data-bind="click: Validate">Submit</button>

You can try it out here: Demo.

like image 153
nemesv Avatar answered Sep 30 '22 18:09

nemesv