Search code examples
javascriptcssknockout.jsknockout-validation

Change knockout validationMessages globally for all pages


I'd like my input validationMessages to be displayed in color red for all pages. How can I do that so it will work globally?

knockout.validation.debug.js has this piece of code

var defaults = {
        registerExtenders: true,
        messagesOnModified: true,
        errorsAsTitle: true,            // enables/disables showing of errors as title attribute of the target element.
        errorsAsTitleOnModified: false, // shows the error when hovering the input field (decorateElement must be true)
        messageTemplate: null,
        insertMessages: true,           // automatically inserts validation messages as <span></span>
        parseInputAttributes: false,    // parses the HTML5 validation attribute from a form element and adds that to the object
        writeInputAttributes: false,    // adds HTML5 input validation attributes to form elements that ko observable's are bound to
        decorateInputElement: false,         // false to keep backward compatibility
        decorateElementOnModified: true,// true to keep backward compatibility
        errorClass: null,               // single class for error message and element
        errorElementClass: 'validationElement',  // class to decorate error element
        errorMessageClass: 'validationMessage',  // class to decorate error message
        allowHtmlMessages: false,       // allows HTML in validation messages
        grouping: {
            deep: false,        //by default grouping is shallow
            observable: true,   //and using observables
            live: false         //react to changes to observableArrays if observable === true
        },
        validate: {
            // throttle: 10
        }
    };

Solution

  • The error messages that are inserted have a class assigned, validationMessage by default. If you want to change the style globally, just set up some css rules for that class and that should be enough.

    .validationMessage
    {
        color: red;
    }
    

    Of course, you also have the option to override the default message class as well.

    ko.validation.init({
        errorMessageClass: 'my-error-class'
    });