jQuery验证-输入已更正后,清除错误消息框 [英] Jquery Validation - clear error message box when input has been corrected

查看:92
本文介绍了jQuery验证-输入已更正后,清除错误消息框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jquery验证以及来自 bassistance.de ,验证错误会显示在屏幕的特定区域,而不是无效的表单元素,这是通过在valid()方法中指定一个空的errorPlacement函数来实现的.

<div id="errbox" style="display: none"></div><br />
<form id="myform" method="post" action="#">
 <fieldset>
    <legend>1. Personal Details</legend>
    <label for="firstName">First Name:</label>
    <input type="text" id="firstName" name="firstName" size="30" required /> 
    <br /><br />
    <label for="lastName">Last Name:</label>
    <input type="text" id="lastName" name="lastName" size="30" required />
 </fieldset>
 <br />
 <input type="submit" value="Go" />            
</form>

只要输入已更正且根据验证规则有效,我希望错误消息消失/清除.如果我取出errorPlacement代码并使消息显示在无效元素旁边,则会发生这种情况,但是如果我在指定的框中显示错误消息,则不会出现这种情况.

这是我的js代码

$("#myform").validate({
 messages: {
    firstName: {required: "Please enter your First Name"},
    lastName: {required: "Please enter your last name -
                          your maiden name if married"},
 },
 invalidHandler: function(form, validator) {
 // This handler will show only one error at time - the first in this instance // 
       var errors = validator.numberOfInvalids();
       if (errors) {
             $("#errbox").html(validator.errorList[0].message);
             $("#errbox").show();
             validator.errorList[0].element.focus();
        } else {
             $("#errbox").hide();
        }
 },       
 errorPlacement: function(error, element) {
            // Override error placement to not show error messages beside elements //
 },    
});

您可以在此处尝试代码: http://jsfiddle.net/E7yPf/

我试图显式声明onKeyUp和onFocusOut属性并将它们设置为true,但没有效果.

这里有人可以帮助或指出正确的方向吗?

谢谢

解决方案

您误解了invalidHandler回调. 根据文档,它仅在表单无效"时在提交点击时触发.换句话说,当没有错误时,将不会显示您的if (errors)条件,因此永远不会调用else hide().

hide()放入success回调中,每当字段通过验证时就会触发该回调.但是,这暴露了invalidHandler逻辑中的缺陷,在该逻辑中,第一个错误消息被清除后,您将看不到其他错误消息.我不确定这是否是最好的做法,但这就是您的意见所表明的.您可以根据需要进行调整.

$("#myform").validate({
    messages: {
        firstName: {
            required: "Please enter your First Name"
        },
        lastName: {
            required: "Please enter your last name - your maiden name if married"
        } // <- removed a trailing comma
    },
    invalidHandler: function (form, validator) {
        // This handler will show only one error at time - the first in this instance // 
        var errors = validator.numberOfInvalids();
        $("#errbox").html(validator.errorList[0].message);
        $("#errbox").show();
        validator.errorList[0].element.focus();
    },
    success: function () {
        $("#errbox").hide();
    },
    errorPlacement: function (error, element) {  // <- do not leave empty
        return false;  
    } // <- removed a trailing comma
});

演示: http://jsfiddle.net/pwgRC/


一些注意事项:

1)此插件仅在jQuery 1.9版中进行了测试,但是,您的jsFiddle使用的是jQuery 1.11.0版.没有已知问题,请谨慎操作.

2)您不能onkeyuponfocusout设置为true. 根据文档,这是无效的选择,因为它已经是默认行为.我见过true破坏了此插件.仅使用false或替代功能.

3)请勿将函数留空.如果要禁用errorPlacement回调函数,只需在其中放置return false.

4)我删除了一些结尾的逗号.在Internet Explorer的旧版本中,这通常是一个技术问题,但在IMO中,这是草率的编程.


替代:

使用errorContainer: "#errbox"选项可以大大改善功能.然后,您可以删除show/hide代码和success选项,因为errorContainer自动处理这些功能.

替代演示: http://jsfiddle.net/pwgRC/1/

然后使用errorLabelContainerwrapper选项,您可以摆脱invalidHandlererrorPlacement函数. (显示所有错误,而不仅显示第一个错误,但我希望您看到这些选项可用.)

替代演示2: http://jsfiddle.net/pwgRC/2/


我建议您通读文档,以便您自己做出最佳决定.

I'm using the jquery validation plus the plugin from bassistance.de, the validation errors are being shown in a specific area of the screen and not besides the invalid form element this is achieved by specifying an empty errorPlacement function in the valid() method.

<div id="errbox" style="display: none"></div><br />
<form id="myform" method="post" action="#">
 <fieldset>
    <legend>1. Personal Details</legend>
    <label for="firstName">First Name:</label>
    <input type="text" id="firstName" name="firstName" size="30" required /> 
    <br /><br />
    <label for="lastName">Last Name:</label>
    <input type="text" id="lastName" name="lastName" size="30" required />
 </fieldset>
 <br />
 <input type="submit" value="Go" />            
</form>

I would like the error messages to disappear/clear whenever the input has been corrected and it's valid against the validation rules. This happens if I take out the errorPlacement code and leave the message appearing besides the invalid element, but it doesn't if I show the error messages in the designated box.

This is my js code

$("#myform").validate({
 messages: {
    firstName: {required: "Please enter your First Name"},
    lastName: {required: "Please enter your last name -
                          your maiden name if married"},
 },
 invalidHandler: function(form, validator) {
 // This handler will show only one error at time - the first in this instance // 
       var errors = validator.numberOfInvalids();
       if (errors) {
             $("#errbox").html(validator.errorList[0].message);
             $("#errbox").show();
             validator.errorList[0].element.focus();
        } else {
             $("#errbox").hide();
        }
 },       
 errorPlacement: function(error, element) {
            // Override error placement to not show error messages beside elements //
 },    
});

You can try the code here: http://jsfiddle.net/E7yPf/

I've tried to explicitly declare the onKeyUp and onFocusOut property and set them to true but it had no effect.

Is there anybody here who can help or point me in the right direction?

Thanks

解决方案

You misunderstand the invalidHandler callback. As per documentation, it only fires on submit click when the form is "invalid". In other words, your if (errors) conditional will never be seen when there are no errors so the else hide() can never be called.

Put hide() inside the success callback which is fired whenever a field passes validation. However, this exposes a flaw in your invalidHandler logic, where you won't see the other error messages after the first one is cleared. I'm not sure if that's the best thing to do, but that's what your comments indicate you want. You can adjust as needed.

$("#myform").validate({
    messages: {
        firstName: {
            required: "Please enter your First Name"
        },
        lastName: {
            required: "Please enter your last name - your maiden name if married"
        } // <- removed a trailing comma
    },
    invalidHandler: function (form, validator) {
        // This handler will show only one error at time - the first in this instance // 
        var errors = validator.numberOfInvalids();
        $("#errbox").html(validator.errorList[0].message);
        $("#errbox").show();
        validator.errorList[0].element.focus();
    },
    success: function () {
        $("#errbox").hide();
    },
    errorPlacement: function (error, element) {  // <- do not leave empty
        return false;  
    } // <- removed a trailing comma
});

DEMO: http://jsfiddle.net/pwgRC/


Some notes:

1) This plugin has only been tested with version 1.9 of jQuery, however, your jsFiddle is using jQuery version 1.11.0. No known issues but proceed with caution.

2) You cannot set onkeyup or onfocusout to true. As per documentation, this is an invalid selection as it's already the default behavior. I've seen true break this plugin. Only use false or an over-riding function.

3) Do not leave a function empty. If you want to disable the errorPlacement callback function, just place a return false inside.

4) I've removed some trailing commas. Mostly a technical problem in older versions of Internet Explorer, but IMO, it's sloppy programming.


Alternative:

Using the errorContainer: "#errbox" option improves the functionality quite a bit. You can then remove your show/hide code and your success option, since errorContainer automatically handles these functions.

Alternative DEMO: http://jsfiddle.net/pwgRC/1/

Then by using the errorLabelContainer and wrapper options, you can get rid of your invalidHandler and errorPlacement functions. (All errors are shown instead of only the first, but I wanted you to see that these options are available.)

Alternative DEMO 2: http://jsfiddle.net/pwgRC/2/


I suggest that you read through the documentation so you can decide best for yourself.

这篇关于jQuery验证-输入已更正后,清除错误消息框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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