使用敲除验证插件的本机规则设置自定义错误消息 [英] Set a custom error message using the native rules of the knockout validation plugin

查看:65
本文介绍了使用敲除验证插件的本机规则设置自定义错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Asp.net MVC3和基因敲除库.我需要做一些客户端验证.我正在研究敲除验证插件.

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

所以我在我的js代码中声明了以下ko.observable值:

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

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

这是我的看法部分:

<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!

推荐答案

以下是创建验证扩展程序的代码.

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
            });
        }
    };
},

如您所见,所有扩展程序都可以接收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 
} }) 

希望这会有所帮助.

这篇关于使用敲除验证插件的本机规则设置自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆