javascript Jquery 验证错误消息没有隐藏,为什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21985027/
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-10-27 22:09:44  来源:igfitidea点击:

Jquery validation error messages are not hiding, why

javascriptjqueryjquery-validateunobtrusive-validation

提问by user1740381

I am using jquery validation and jquery unobtrusive validation plugins. I am trying to hide error message, but error message are not hiding. I have created a js fiddle:

我正在使用 jquery 验证和 jquery unobtrusive 验证插件。我试图隐藏错误消息,但错误消息没有隐藏。我创建了一个 js 小提琴:

Fiddle Link

小提琴链接

Following is the code which i used in the fiddle:

以下是我在小提琴中使用的代码:

Html

html

<form id="form">
    Name:
    <input data-val="true" data-val-length="The field First Name must be a string with a minimum length of 3 and a maximum length of 15." data-val-length-max="15" data-val-length-min="3" name="FirstName" type="text" />
    <span class="field-validation-valid help-block" data-valmsg-for="FirstName" data-valmsg-replace="true"></span>
</form>
<button id="hide">Hide</button>

Hide

隐藏

JS

JS

$("#hide").click(function(){
   $("#form").data("validator").hideErrors();
});

What i am missing here and why hideErrors() function are not working ??

我在这里缺少什么以及为什么 hideErrors() 函数不起作用?

Edit

编辑

I don't know why you guys are not keeping jquery unobtrusive validation in mind while giving answers. Almost all answer are just focusing on how to hide error messages without worrying about the existing functionality which could be break if we just hide the message. I already mention that i want the answer of

我不知道你们为什么在给出答案时没有记住 jquery 不显眼的验证。几乎所有的答案都只关注如何隐藏错误消息而不用担心如果我们只是隐藏消息可能会破坏现有的功能。我已经提到我想要答案

Why hideErrors() function of jquery validator object is not working ?

为什么 jquery 验证器对象的 hideErrors() 函数不起作用?

I have also created a simplest possible fiddle which demonstrate my problem, check this.

我还创建了一个最简单的小提琴来演示我的问题,检查这个

回答by Gaurav

If you want to hide validation error messages, than you should use resetFormfunction instead of hideErrorsfunction. As other mentioned in their answers, resetForminternally call hideErrorsfunction.

如果要隐藏验证错误消息,则应使用resetForm函数而不是hideErrors函数。正如其他人在他们的回答中提到的,resetForm 在内部调用hideErrors函数。

But here's the twist comes, when you will try to use resetFormfunction it will not work because of the way jquery.validate.unobtrusiveplugin works.

但这里的转折来了,当您尝试使用resetForm函数时,它不会起作用,因为jquery.validate.unobtrusive插件的工作方式。

jquery.validate.unobtrusiveplugin override the errorClassand errorElementproperty of jquery.validateplugin.

jquery.validate.unobtrusive插件覆盖errorClasserrorElement财产jquery.validate插件。

From jquery.validate.unobtrusive plugin code Line-109

来自 jquery.validate.unobtrusive 插件代码 Line-109

    .... 
    if (!result) {
        result = {
            options: {  
                errorClass: "input-validation-error",
                errorElement: "span",
                errorPlacement: $.proxy(onError, form),
    ...

So when you will call resetFormfunction on validator's object, jquery.validateplugin can't find error labels to remove so validation error message will not remove.

因此,当您在验证器的对象上调用resetForm函数时,jquery.validate插件找不到要删除的错误标签,因此不会删除验证错误消息。

Now you have two options to remove error messages:

现在您有两个选项可以删除错误消息:

Option - 1

选项1

You can edit jquery.validate.unobtrusiveplugin code and replace errorClassand errorElementvalues with the following values:

您可以编辑jquery.validate.unobtrusive插件代码并将errorClasserrorElement值替换为以下值:

    errorClass: "error",
    errorElement: "label",

These are the default values which jquery.validateplugin use.

这些是jquery.validate插件使用的默认值。

Option - 2

选项 - 2

You can write your own code which will do the trick and by this way you do not have to modify the plugin code. Here is the code which you can usewith little modifications mentioned below:

您可以编写自己的代码来实现这一点,这样您就不必修改插件代码。这是您只需稍加修改即可使用的代码

        // get the form 
        var form = $("#formId");

        // get validator object
        var validator = form.validate();

        // get errors that were created using jQuery.validate.unobtrusive
        var errors = form.find(".field-validation-error span");

        // trick unobtrusive to think the elements were succesfully validated
        // this removes the validation messages
        errors.each(function () { validator.settings.success($(this)); })

        //this is optional, only needed if you defined 
        //custom unhighlight function  
        if (validator.settings.unhighlight) {
            for (i = 0, elements = validator.invalidElements() ; elements[i]; i++) {
                validator.settings.unhighlight.call(validator, elements[i], validator.settings.errorClass, validator.settings.validClass);
            }
        }

回答by GuyT

You could use $(".help-block").toggle();or $(".help-block").hide();to fix this.

您可以使用$(".help-block").toggle();$(".help-block").hide();来解决此问题。

http://jsbin.com/leyacefi/10/edit?html,js,output

http://jsbin.com/leyacefi/10/edit?html,js,output

I've made a workaround. Check if it fit to your needs:

我已经做了一个解决方法。检查它是否符合您的需求:

$("#hide").click(function(){
    $(".help-block").hide();
});

$('#form').keyup(function(){
  $(".help-block").show();
});

http://jsbin.com/leyacefi/11/

http://jsbin.com/leyacefi/11/

To answer your question:

回答你的问题:

The function hideErrorsis calling this.addWrapper( this.toHide ).hide();so it first runs the function addWrapperthat returns the context and after that it is calling the hidefunction. The function hidecalls the showHidefunction and one of the paramets is elements. elements.lengthwill be 0 and therefore it will never reach till the elem.style.display = show ? values[ index ] || "" : "none";where the CSS will be set. So, the property will never change.

该函数hideErrors正在调用,this.addWrapper( this.toHide ).hide();因此它首先运行addWrapper返回上下文的hide函数,然后调用该函数。该函数hide调用该showHide函数,其中一个参数是elementselements.length将是 0,因此它永远不会到达elem.style.display = show ? values[ index ] || "" : "none";设置 CSS的位置。所以,属性永远不会改变。

回答by Adel

Your code should be like the following:

您的代码应如下所示:

$(document).ready(function() { 
        $("#hide").click(function(){ 
            $("span.help-block").hide();
        }); 

}); 

回答by venugopal

I would recommend you to read the documentation before using any plugin. If you see the validator plugin documentation, it is clearly mentioned that

我建议您在使用任何插件之前阅读文档。如果你看到验证器插件文档,它清楚地提到

    Validator

The validate method returns a Validator object that has a few public methods that you can  use to trigger validation programmatically or change the contents of the form. The validator object has more methods, but only those documented here are intended for usage

The method .hideErrors() is not listed in the documentation. So as per documentation, you shouldn't use it.

方法 .hideErrors() 未在文档中列出。所以根据文档,你不应该使用它。

But in javascript(you can say jquery) many are possible. So even if they dont allow you to call it on the jquery object, you can call it on DOM .

但是在 javascript(你可以说 jquery)中有很多是可能的。因此,即使他们不允许您在 jquery 对象上调用它,您也可以在 DOM 上调用它。

Simply use like this.

简单地这样使用。

   $("#hide").click(function(){
   $("#form").data("validator")[0].hideErrors();
});