为jQuery Validate插件添加自定义错误条件和常规错误消息 [英] Add Custom Error Condition and General Error Message for jQuery Validate Plugin

查看:260
本文介绍了为jQuery Validate插件添加自定义错误条件和常规错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序解决方案,以便为我提供有限的页面空间,因此无法为每个必填字段应用包含的错误消息。因此,我正在尝试创建一个解决方案,突出显示受影响的必填字段,并仅为表单中的电子邮件地址,电话和密码等指定字段创建自定义消息。

I am working on an in application solution for affords me limited page real estate and therefore cannot apply contained error messages for every required field. I therefore am trying to create a solution that would highlight the affected required fields and only create a custom message for specified fields like email address, telephone and password in my form.

我目前正在使用基本shell(适用于包含的消息)

I am presently working with the basic shell(which is working fine for contained messages)

    var v = $("form").validate({
        rules: {
            email: {
                required: true,
                email: true                 
            },
            confirmEmail: {
                required: true,
                email: true,
                equalTo: "#email"
            }
        },
        messages: {
            email: "Please enter a valid email address",
            confirmEmail: {
                required: "Please enter a valid verify email address",
                equalTo: "Both email addresses must be the same."
            }
        },
        errorContainer: errcontainer,
        errorLabelContainer: $("ol", errcontainer),
        wrapper: 'li',
        onkeyup: false,
        onblur: false
    });     

预先感谢您的任何帮助或建议。

Thanks in advance for any help or advice.

推荐答案

你要做的是实现 showErrors 挂钩。

您将传递错误消息的映射,然后与生成它们的表单元素关联的那些相同消息的数组。

You get passed a map of the error messages, and then an array of those same messages associated with the form element that produced them.

然后你最好的选择是获取默认处理程序的副本(称为 validate插件中的defaultShowErrors 并稍微修改(仅显示您关注的标签)。

Your best bet is then to just take a copy of the default handler (called defaultShowErrors in the validate plugin) and modify it slightly (to only show labels for the ones you care about).

你会然后在你的验证选项中有这样的东西:

You'd then have something like this in your validate options:

showErrors: function(errorMap, errorList) {
    for (var i = 0; this.errorList[i]; i++) {
        var error = this.errorList[i];
        //this is the only real part you modify
        if (error.element.id == 'email' || error.element.id == 'confirmEmail') {
            this.showLabel(error.element, error.message);
        }
        this.settings.highlight && this.settings.highlight.call(this, error.element, this.settings.errorClass, this.settings.validClass);
    }
    //a whole bunch more stuff after this, from jquery.validate.js
}

在这里看到这个想法: http://jsfiddle.net/ryleyb/ D3tfu /

See this idea in action here: http://jsfiddle.net/ryleyb/D3tfu/

这篇关于为jQuery Validate插件添加自定义错误条件和常规错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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