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

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

问题描述

我正在使用 Asp.net MVC3 和 Knockoutjs 库.我需要做一些客户端验证.我正在探索淘汰验证插件.

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天全站免登陆