Add CSS Class with Knockout Validator
Asked Answered
I

1

15

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?

Ism answered 17/8, 2012 at 11:40 Comment(0)
J
22

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)

Junta answered 17/8, 2012 at 14:44 Comment(2)
Plus 1 for the mention of decorateInputElementAlmena
And the global configuration is done in ko.validation.init not ko.validation.configuration.Windblown

© 2022 - 2024 — McMap. All rights reserved.