Set a custom error message using the native rules of the knockout validation plugin

Mdb picture Mdb · May 11, 2012 · Viewed 19.9k times · Source

I am using Asp.net MVC3 and knockoutjs library. I need to do some client side validation. I am exploring the knockout validation plugin.

So I declare the following ko.observable value in my js code:

 var numberValue = ko.observable().extend({ number: true }) 

This is my view part:

<input data-bind = "value: numberValue " />

When the user enters some value that is not a number an error message is displayed : "Please enter a number". Can I display a different error message but still using the native rules? I do not want to write custom validation logic just for this. Any help with some working example will be greatly appreciated. Thank You!

Answer

madcapnmckay picture madcapnmckay · May 11, 2012

Here is the code that creates the validation extenders.

addExtender: function (ruleName) {
    ko.extenders[ruleName] = function (observable, params) {
        //params can come in a few flavors
        // 1. Just the params to be passed to the validator
        // 2. An object containing the Message to be used and the Params to pass to the validator
        //
        // Example:
        // var test = ko.observable(3).extend({
        //      max: {
        //          message: 'This special field has a Max of {0}',
        //          params: 2
        //      }
        //  )};
        //
        if (params.message) { //if it has a message object, then its an object literal to use
            return ko.validation.addRule(observable, {
                rule: ruleName,
                message: params.message,
                params: params.params || true
            });
        } else {
            return ko.validation.addRule(observable, {
                rule: ruleName,
                params: params
            });
        }
    };
},

As you can see all the extenders can receive a params object or an object literal with the params and a custom message. So in your case.

var numberValue = ko.observable().extend({ number: { 
    message: "some custom message", 
    params: true 
} }) 

Hope this helps.