【问题标题】:jQuery Validation with a custom error message which includes a confirmation带有包含确认的自定义错误消息的 jQuery 验证
【发布时间】:2014-02-02 06:30:59
【问题描述】:

我正在尝试在地址街道字段上使用 jQuery 验证插件 (http://jqueryvalidation.org/),人们必须在该字段中确认他们的地址是否不包含门牌号(有些人只是忘记写它或其他什么)。

所以我编写了一个自定义规则,并用两个按钮扩展了错误消息,如下所示:

// comes from an external file
jQuery.extend(jQuery.validator.methods, {
    containsnum: function(value, element) {
        return this.optional(element) || /^.*(\d).*$/.test(value);
    }
});
// comes from an external file
jQuery.extend(jQuery.validator.messages, {
    containsnum: "Does this address have a house number? <button id='yes' class='btn btn-mini'>yes</button> <button id='no' class='btn btn-mini'>no</button>"
});

然后是实际的验证码

$(document).ready(function() {
    var xx = $('#customer-data-form').validate({
        debug:true,     

        ignore: ":hidden",
        rules: {
            Anschrift: {
                containsnum:true
            }
        }
    });
    /* check for house number */
    $(document).on('click',"#no",function(e){
        console.log('no')
        e.preventDefault();
        $('#Anschrift').rules( "remove", "containsnum" );
        xx.element('#Anschrift');
    });
    $(document).on('click',"#yes",function(e){
        console.log('yes')  
        e.preventDefault();
        $('#Anschrift').focus();
    });
});

它工作得很好,但在某些情况下,确认(和删除规则)只在第二次单击是/否按钮时起作用。

我已经设置了重现此行为的步骤。

http://jsfiddle.net/CC3zH/2/

我们的目标是,在任何情况下都可以在第一次单击时确认该消息,然后我希望得到提示,如何将按钮与错误消息字符串分开。 我已经尝试过 errorPlacement 等,但如果不重写所有函数以显示错误,则没有找到简单的解决方案。

感谢任何提示。

【问题讨论】:

    标签: javascript jquery validation confirmation


    【解决方案1】:

    这是focusoutclick 事件如何交互的问题。如果您环顾四周,您会发现在失去焦点的元素上也触发了focusout 事件时,click 事件未正确触发是一个非常常见的问题。提出了许多解决方案,但一种适用于您的情况的解决方案是将您的$.on 处理程序更改为mousedown 而不是click,如下所示:

    $('#customer-data-form').on('mousedown',"#no",function(e){
        console.log('no')
        e.preventDefault();
        $('#Anschrift').rules( "remove", "containsnum" );
        xx.element('#Anschrift');
    });
    $('#customer-data-form').on('mousedown',"#yes",function(e){
        console.log('yes')  
        e.preventDefault();
        $('#Anschrift').focus();
    });
    

    在这里工作: http://jsfiddle.net/ryleyb/CC3zH/3/

    【讨论】:

    • 我已将小提琴更新为 jsfiddle.net/ryleyb/CC3zH/4,将 xx.element('#Anschrift'); 添加到“是”按钮,否则它会验证所有字段。
    猜你喜欢
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 2015-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多