Search code examples
javascriptknockout.jsknockout-validation

KnockoutJS Validate - getting element's css class added


I'm having trouble getting knockout validate to add an error css class to my input.

I have it configured like this:

var knockoutValidationSettings = {
    insertMessages: true,
    decorateElement: true,
    errorMessageClass: 'error',
    errorElementClass: 'error',
    errorClass: 'error',
    errorsAsTitle: true,
    parseInputAttributes: false,
    messagesOnModified: true,
    decorateElementOnModified: true
};

data.vm = new vmFunc();

ko.applyBindingsWithValidation(data.vm, $('#claimsSettingsSubmodule')[0], knockoutValidationSettings);

The span is getting added with the appropriate css class, but the input is remaining unchanged.

The input's html looks like this

<input type="text" id="claims-settings-referrer-name" data-bind="value: referrerName" />

It seems to work if I do this

<input type="text" id="claims-settings-referrer-name" data-bind="value: referrerName, validationElement: referrerName" />

but that's less than optimal to say the least.


Solution

  • In order to automatically decorate your the input elements with the errorElementClass you need to set the decorateInputElement property to true in your knockoutValidationSettings

    var knockoutValidationSettings = {
        insertMessages: true,
        decorateElement: true,
        errorMessageClass: 'error',
        errorElementClass: 'error',
        errorClass: 'error',
        errorsAsTitle: true,
        parseInputAttributes: false,
        messagesOnModified: true,
        decorateElementOnModified: true,
        decorateInputElement: true
    };
    

    The decorateElementOnModified only works together with the validationElement binding as you've already noted.