本文介绍了有效与验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习jQuery,偶然发现了一个奇怪的问题(也许仅对我来说很奇怪).因此,这里去:我的应用程序中有一个ID为mainform的表格.现在,我想使用jQuery验证表单.我也想将无效字段设置为蓝色.为此,我添加了CSS

I am trying to learn jQuery and have stumbled across a strange problem (perhaps strange only to me). So here goes:I have a form with id mainform in my app. Now I wanted to validate the form with jQuery. Also I wanted to set the invalid fields in blue color. For that I added css

.error{
  background-color:blue;
}

当我在控制台中运行$('form#mainform').valid();时,我得到了亮点,并且一切正常.但是,当我运行$('form#mainform').validate();时,得到的数据很多,什么也没发生.

When I run $('form#mainform').valid(); in the console, I get the highlights and everything works fine. However when I run $('form#mainform').validate();, I get lots of data and nothing happens.

此外,如果我在validate()之前运行.valid(),则各种选项(例如错误放置等)似乎都不起作用.

Also if I run .valid() before validate(), various options such as error placement etc. don't seem to work.

我想知道它们之间的区别,为什么它们的行为如此不同以及应该在哪里使用它们.如果有人能指出正确的方向,我将不胜感激.

I want to know the difference between these, why they are behaving so differently and where they should be used. I will appreciate if anyone can point me in right direction.

注意:我正在使用jquery.validate.js

Note: I am using jquery.validate.js

推荐答案

有效和验证之间存在一些差异.有趣的是,尽管文档指出

There are several differences between valid and validate. Interestingly, although the docs state that

实际上并非如此,因为无论如何有效的调用validate().

this isn't actually the case, as valid calls validate() anyway.

两个主要区别是

  1. 如果要将选项传递到插件中,则必须调用validate({...})
  2. validate()不会突出显示任何错误,而valid()会突出显示任何错误.您可以说,valid执行急切"验证,而validate设置懒惰"验证,基本上,如果您调用validate(),则您不会在页面上看到任何立即更改,而使用validate()则可以. >
  3. valid可以在表单元素的子集上调用,而validate必须在表单本身上调用:

  1. If you want to pass options into the plugin, you must call validate({...})
  2. validate() doesn't highlight any errors, whereas valid() does. You could say that valid performs 'eager' validation whereas validate sets up a 'lazy' validation, basically if you call validate() you won't see any immediate change on the page, whereas with valid() you might.
  3. valid can be called on a subset of form elements, whereas validate must be called on the form itself:

$('form').validate({/*这里的选项*/});

$('form').validate({/* options here */});

$('.myfields').valid()

$('.myfields').valid()

这篇关于有效与验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 14:21