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 :
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?
There are a few problems with your current approach:
ko.validation.ruleit should beko.validation.rulesko.validation.registerExtenders();should be done before you first try to use the custom validator.In order the validation displayed you need to bind it somewhere with
validationMessagebinding:So the fixed script:
And the HTML:
You can try it out here: Demo.