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

3

21

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!

Geometrize answered 11/5, 2012 at 13:46 Comment(0)
C
36

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.

Curvy answered 11/5, 2012 at 15:18 Comment(2)
So, wait - it's possible to set the ko.validation.rules.pattern.message but not the other ones!? I just tried with validation.rules.minLength and it didn't work - I can see the value being set on the object, but then it just uses the original value.Dismast
as shown above you can also use {0} as a placeholder for the parameter : eg. this.foo = ko.observable('').extend({ max: { params: 5, message: "The maximum value is {0}!" } });Volz
B
35

you can just add validate property like this

 emailAddress: ko.observable().extend({  // custom message
        required: { message: 'Please supply your email address.' }
    }),
Bulge answered 7/9, 2013 at 20:23 Comment(2)
yeap, works well and it is much better answer then the one above. Use provided solutions as long as it is possibleMerkle
I support your suggestion with the contribution of official information: github.com/Knockout-Contrib/Knockout-Validation/wiki/… In the first paragraph you can read "var myObj = ko.observable().extend({ required: { params: true, message: 'This field is required.' } });"Dupery
B
2

The existing answers are correct. However, if you want to change the message for a validator that already accepts other parameters, you have to wrap those existing parameters in a new object named params.

ko.observable().extend({
    unique: {
        params: {
            collection: foo,
            valueAccessor: function(item) {
                return item.bar();
            }
        },
        message: 'some custom message'
    }
}
Battaglia answered 6/9, 2017 at 8:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.