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

醉酒当歌 提交于 2019-12-30 07:54:12

问题


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!


回答1:


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.




回答2:


you can just add validate property like this

 emailAddress: ko.observable().extend({  // custom message
        required: { message: 'Please supply your email address.' }
    }),



回答3:


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'
    }
}


来源:https://stackoverflow.com/questions/10552625/set-a-custom-error-message-using-the-native-rules-of-the-knockout-validation-plu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!