Reputation: 8487
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?
Upvotes: 10
Views: 6894
Reputation: 195
You could also use the equal native validator:
self.Approve = ko.observable(false).extend({
equal: { params: true, message: 'check must be ticked' }
});
Upvotes: 5
Reputation: 139758
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.
Upvotes: 10