Search code examples
javascriptknockout.jsknockout-validation

Can you use the parameters in a Knockout custom validator inside the message?


I have made a custom validator much like the one that can be found here.

The intent of my validator is to be generic enough that it can be used in other places. This particular one validates the filetype extensions passed into it, and returns true if the observable is of a valid filetype. I would like to pass a custom error message that includes these file types to alert the user of what extensions are acceptable.

IE

ko.validation.rules['validateFileTypeExtensions'] = {
    validator: function (fileName, validExtensions) {
        var isValidExtension = false;
        var extension = fileName.split('.').pop();
        validExtensions.forEach(function(validExtension){
            if(extension == validExtension)
                isValidExtension = true;
        });
        return isValidExtension;
    },
    // At this point message does not have access to the validExtensions
    // that were passed into the validator. Is there a way to get them here?
    message: 'Please chose a file with an acceptable extension ({0}).'
};

ko.validation.registerExtenders();

//the valid file extensions are passed into the validator.

var myCustomObj = ko.observable().extend({ validateFileTypeExtensions: ['xls', 'xlsx'] });

As you can see, the 'message' does not have access to the validExtensions variable. Is there some way that I'm just not aware of to access that value within the validator?


Solution

  • The value will be inserted in place of the {0} part of your message string. If you wanted more control over how the message was formatted, make message a function where you return your formatted message.

    e.g.,

    ko.validation.rules.myValidator = {
        validator: function (...) {
            ...
        },
        message: function (params, observable) {
            return 'invalid, was expecting ' + params + ' but got ' + observable();
        }
    };
    

    If you want to completely override the message from the extender, rather than passing in your normal parameters in the extender, pass in a validator configuration with your params and the modified message.

    var obs = ko.observable().extend({
        myValidator: { params: 123, message: 'oops' }
    });