Add CSS Class with Knockout Validator

12,607

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)

Share:
12,607
CallumVass
Author by

CallumVass

Updated on June 15, 2022

Comments

  • CallumVass
    CallumVass about 2 years

    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?

  • Matt Johnson
    Matt Johnson almost 9 years
    Plus 1 for the mention of decorateInputElement
  • Alex
    Alex about 8 years
    And the global configuration is done in ko.validation.init not ko.validation.configuration.