如何清除 jQuery 验证错误消息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2086287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:44:16  来源:igfitidea点击:

How to clear jQuery validation error messages?

jqueryjquery-validate

提问by Vicky

I am using the jQuery validation plugin for client side validation. Function editUser()is called on click of 'Edit User' button, which displays error messages.

我正在使用 jQuery 验证插件进行客户端验证。editUser()单击“编辑用户”按钮时调用该函数,该按钮显示错误消息。

But I want to clear error messages on my form, when I click on 'Clear' button, that calls a separate function clearUser().

但是我想清除表单上的错误消息,当我点击“清除”按钮时,调用一个单独的函数clearUser()

function clearUser() {
    // Need to clear previous errors here
}

function editUser(){
    var validator = $("#editUserForm").validate({
        rules: {
            userName: "required"
        },
        errorElement: "span",
        messages: {
            userName: errorMessages.E2
        }
    });

    if(validator.form()){
        // Form submission code
    }
}

回答by Parrots

You want the resetForm()method:

你想要的resetForm()方法:

var validator = $("#myform").validate(
   ...
   ...
);

$(".cancel").click(function() {
    validator.resetForm();
});

I grabbed it from the source of one of their demos.

我从他们一个演示的来源中获取了它。

Note: This code won't work for Bootstrap 3.

注意:此代码不适用于 Bootstrap 3。

回答by Travis J

I came across this issue myself. I had the need to conditionally validate parts of a form while the form was being constructed based on steps (i.e. certain inputs were dynamically appended during runtime). As a result, sometimes a select dropdown would need validation, and sometimes it would not. However, by the end of the ordeal, it needed to be validated. As a result, I needed a robust method which was not a workaround. I consulted the source code for jquery.validate.

我自己遇到了这个问题。我需要在基于步骤构建表单时有条件地验证表单的某些部分(即某些输入在运行时动态附加)。因此,有时选择下拉列表需要验证,有时则不需要。然而,在磨难结束时,它需要得到验证。因此,我需要一个强大的方法,这不是一种解决方法。我查阅了jquery.validate.

Here is what I came up with:

这是我想出的:

  • Clear errors by indicating validation success
  • 通过指示验证成功清除错误
  • Call handler for error display
  • 错误显示的调用处理程序
  • Clear all storage of success or errors
  • 清除成功或错误的所有存储
  • Reset entire form validation

    Here is what it looks like in code:

    function clearValidation(formElement){
     //Internal $.validator is exposed through $(form).validate()
     var validator = $(formElement).validate();
     //Iterate through named elements inside of the form, and mark them as error free
     $('[name]',formElement).each(function(){
       validator.successList.push(this);//mark as error free
       validator.showErrors();//remove error messages if present
     });
     validator.resetForm();//remove error class on name elements and clear history
     validator.reset();//remove all error and success data
    }
    //used
    var myForm = document.getElementById("myFormId");
    clearValidation(myForm);
    

    minified as a jQuery extension:

    $.fn.clearValidation = function(){var v = $(this).validate();$('[name]',this).each(function(){v.successList.push(this);v.showErrors();});v.resetForm();v.reset();};
    //used:
    $("#formId").clearValidation();
    
  • 重置整个表单验证

    这是它在代码中的样子:

    function clearValidation(formElement){
     //Internal $.validator is exposed through $(form).validate()
     var validator = $(formElement).validate();
     //Iterate through named elements inside of the form, and mark them as error free
     $('[name]',formElement).each(function(){
       validator.successList.push(this);//mark as error free
       validator.showErrors();//remove error messages if present
     });
     validator.resetForm();//remove error class on name elements and clear history
     validator.reset();//remove all error and success data
    }
    //used
    var myForm = document.getElementById("myFormId");
    clearValidation(myForm);
    

    缩小为 jQuery 扩展:

    $.fn.clearValidation = function(){var v = $(this).validate();$('[name]',this).each(function(){v.successList.push(this);v.showErrors();});v.resetForm();v.reset();};
    //used:
    $("#formId").clearValidation();
    
  • 回答by Nick Craver

    If you want to simply hide the errors:

    如果您只想隐藏错误:

    $("#clearButton").click(function() {
      $("label.error").hide();
      $(".error").removeClass("error");
    });
    

    If you specified the errorClass, call that class to hide instead error(the default) I used above.

    如果您指定了errorClass, 调用该类来隐藏error(默认)我在上面使用过。

    回答by Juri

    If you didn't previously save the validators apart when attaching them to the form you can also just simply invoke

    如果您之前没有在将验证器附加到表单时将它们分开保存,您也可以简单地调用

    $("form").validate().resetForm();
    

    as .validate()will return the same validators you attached previously (if you did so).

    as.validate()将返回您之前附加的相同验证器(如果您这样做了)。

    回答by Abhijit Mazumder

    If you want to do it without using a separate variable then

    如果你想在不使用单独变量的情况下做到这一点,那么

    $("#myForm").data('validator').resetForm();
    

    回答by Meower68

    Unfortunately, validator.resetForm()does NOT work, in many cases.

    不幸的是,validator.resetForm()在许多情况下不起作用。

    I have a case where, if someone hits the "Submit" on a form with blank values, it should ignore the "Submit." No errors. That's easy enough. If someone puts in a partial set of values, and hits "Submit," it should flag some of the fields with errors. If, however, they wipe out those values and hit "Submit" again, it should clear the errors. In this case, for some reason, there are no elements in the "currentElements" array within the validator, so executing .resetForm()does absolutely nothing.

    我有一个案例,如果有人在带有空白值的表单上点击“提交”,它应该忽略“提交”。没有错误。这很容易。如果有人输入了部分值,并点击了“提交”,它应该标记一些有错误的字段。但是,如果他们清除了这些值并再次点击“提交”,则应清除错误。在这种情况下,由于某种原因,验证器中的“currentElements”数组中没有元素,因此执行.resetForm()完全没有任何作用。

    There are bugs posted on this.

    有错误张贴在此。

    Until such time as they fix them, you need to use Nick Craver's answer, NOT Parrots' accepted answer.

    在他们修复它们之前,您需要使用 Nick Craver 的答案,而不是 Parrots 接受的答案。

    回答by Brain Balaka

    You can use:

    您可以使用:

    $("#myform").data('validator').resetForm();
    

    回答by Karra

    I think we just need to enter the inputs to clean everything

    我认为我们只需要输入输入即可清理所有内容

    $("#your_div").click(function() {
      $(".error").html('');
      $(".error").removeClass("error");
    });
    

    回答by Chintsu

    If you want just clear validation labels you can use code from jquery.validate.js resetForm()

    如果您只想清除验证标签,您可以使用 jquery.validate.js resetForm() 中的代码

    var validator = $('#Form').validate();
    
    validator.submitted = {};
    validator.prepareForm();
    validator.hideErrors();
    validator.elements().removeClass(validatorObject.settings.errorClass);
    

    回答by Sebastian Xawery Wi?niowiecki

    For those using Bootstrap 3 code below will clean whole form: messages, icons and colors...

    对于那些使用下面的 Bootstrap 3 代码的人来说,将清理整个表单:消息、图标和颜色......

    $('.form-group').each(function () { $(this).removeClass('has-success'); });
    $('.form-group').each(function () { $(this).removeClass('has-error'); });
    $('.form-group').each(function () { $(this).removeClass('has-feedback'); });
    $('.help-block').each(function () { $(this).remove(); });
    $('.form-control-feedback').each(function () { $(this).remove(); });