Add CSS Class with Knockout Validator

CallumVass picture CallumVass · Aug 17, 2012 · Viewed 12.5k times · Source

I want to add a CSS Class to a select element in my view, my view model has a property which I've extended using Knockout-Validation:

self.selectedRootCause = ko.observable().extend({
    required: true
});

Then my select is like so:

<form data-bind="submit: closeComplaint" method="post"> 
    <select data-bind="options: rootCauses, 
                            optionsText: 'RootCauseText', 
                            value: selectedRootCause, 
                            optionsCaption: 'Choose..',
                            validationOptions: { errorElementClass: 
                                                 'input-validation-error' }">
    </select>

    <input type="submit" value="Close Complaint" />
</form>

My closeComplaint function looks like so:

self.closeComplaint = function () {
    if (self.errors().length == 0) {
        $.ajax({
            url: '@Url.Action("CloseComplaint")',
            data: new DetailsComplaintAdmin(self.currentComplaint(),
                                        self.selectedRootCause().RootCauseId
                ),
            success: function (data) {
                console.log(data);
            }
        });
    }
}

Just for completion, here is my self.errors() function:

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

The problem is the class input-validation-error doesn't appear to be added to my select input when I submit my form? Any ideas?

Answer

Luffy picture Luffy · Aug 17, 2012

Checkout this link

Its said that you have to set decorateElement to true for applying CSS classes to input tags.
So when i apply that parameter globally it works :

ko.validation.configure({ 
    decorateElement : true
});

Checkout this jsfiddle demo

Note: In more recent versions of the Knockout Validation library, the decorateElement configuration option has been renamed to decorateInputElement(details)