Javascript 如何在 jQuery 验证中显示错误?

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

How can I show errors in jQuery validation?

javascriptjqueryvalidationjquery-validate

提问by Vaibhav Jain

Do we have any function which returns all the error messages while validating a form?

我们是否有任何函数可以在验证表单时返回所有错误消息?

I have tried using the defaultshowerros()function but it returns the error message for the element it is currently validating. How can I get all the error messages of the whole form?

我曾尝试使用defaultshowerros()函数,但它返回当前正在验证的元素的错误消息。如何获取整个表单的所有错误消息?

回答by Nick Craver

If you store a reference to the validator, for example:

如果您存储对验证器的引用,例如:

var validator = $("form").validate();

You can call .errors()or .invalidElements()at any time on it, for example:

您可以随时调用.errors().invalidElements(),例如:

var errors = validator.errors(); //get the error elements, the actual labels
var errors = validator.invalidElements(); //the invalid elements themselves

If you're not really after the errors and just want them to appear in once place, use the built-in errorLabelContainerand wrapperoptions, for example:

如果您不是真的在处理错误,而只是希望它们出现在一次,请使用内置errorLabelContainerwrapperoptions,例如:

<ul id="errors"></ul>

And reference that:

并参考:

$("form").validate({ errorLabelContainer: "#errors", wrapper: "li" });

And your errors would appear all in that list, which is also automatically shown/hidden if there are/aren't any errors.

并且您的错误将全部出现在该列表中,如果有/没有任何错误,它也会自动显示/隐藏。

回答by Belinda

The validation plugin should show an error beside the field where the error is. Are you using id's for your input boxes? If so use a name as well and give jquery the value of the name attribute in your rules and messages. Hope this helps.

验证插件应该在错误所在的字段旁边显示一个错误。你的输入框用的是id吗?如果是这样,请使用名称并在规则和消息中为 jquery 提供名称属性的值。希望这可以帮助。

回答by Sean Kendle

Late to the party, but I found you can also instantiate the validate()object with a invalidHandler()function:

迟到了,但我发现你也可以validate()用一个invalidHandler()函数实例化对象:

var $jqvForm = $(".jqvForm").validate({
    invalidHandler: function(e, validation){
        console.log("invalidHandler : event", e);
        console.log("invalidHandler : validation", validation);
    }
});

The validationvariable contains a variable invalid(object) with form items and their error messages.

validation变量包含一个invalid带有表单项及其错误消息的变量(对象)。