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?
There are a few problems with your current approach:
ko.validation.rule
it should be ko.validation.rules
ko.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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With