jQuery validator 主页

github地址

demo学习

效果:

  Validate forms like you've never validated before!

自定义Validate:

  • doesn't jQuery make it easy to write your own validation plugin?

    • Sure, but there are still a lot of subtleties to take care of:

      • You need a standard library of validation methods (such as emails, URLs, credit card numbers).
      • You need to place error messages in the DOM and show and hide them when appropriate.
      • You want to react to more than just a submit event, like keyup and blur.
      • You may need different ways to specify validation rules according to the server-side enviroment you are using on different projects.

集成好的、拿来即用的Validate

  • there are a lot of non-jQuery-based solutions (which you'd avoid since you found jQuery) and some jQuery-based solutions
  • This particular one is one of the oldest jQuery plugins (started in July 2006) and has proved itself in projects all around the world.
    • There is also an article discussing how this plugin fits the bill of the should-be validation solution.
    • <form class="cmxform" id="commentForm" method="get" action="">
      <fieldset>
      <legend>Please provide your name, email address (won't be published) and a comment</legend>
      <p>
      <label for="cname">Name (required, at least 2 characters)</label>
      <input id="cname" name="name" minlength="2" type="text" required>
      </p>
      <p>
      <label for="cemail">E-Mail (required)</label>
      <input id="cemail" type="email" name="email" required>
      </p>
      <p>
      <label for="curl">URL (optional)</label>
      <input id="curl" type="url" name="url">
      </p>
      <p>
      <label for="ccomment">Your comment (required)</label>
      <textarea id="ccomment" name="comment" required></textarea>
      </p>
      <p>
      <input class="submit" type="submit" value="Submit">
      </p>
      </fieldset>
      </form>
      <script>
      $("#commentForm").validate();
      </script>
      • A single line of jQuery to select the form and apply the validation plugin, plus a few annotations on each element to specify the validation rules.

        • Of course that isn't the only way to specify rules. You also don't have to rely on those default messages, but they come in handy when starting to setup validation for a form.
    • 效果
      • After trying to submit an invalid form, the first invalid element is focused, allowing the user to correct the field.

        • If another invalid field – that wasn't the first one – was focused before submit, that field is focused instead, allowing the user to start at the bottom if he or she prefers.
      • Before a field is marked as invalid, the validation is lazy:
        • Before submitting the form for the first time, the user can tab through fields without getting annoying messages – they won't get bugged before having the chance to actually enter a correct value
      • Once a field is marked invalid, it is eagerly validated:
        • As soon as the user has entered the necessary value, the error message is removed
      • If the user enters something in a non-marked field, and tabs/clicks away from it (blur the field), it is validated
        • obviously the user had the intention to enter something, but failed to enter the correct value
    • 原理
      • That behaviour can be irritating when clicking through demos of the validation plugin

        • it is designed for an unobtrusive user experience, annoying the user as little as possible with unnecessary error messages.

API

two terms are used very often, so it's important that you know their meaning in the context of the validation plugin:

Plugin methods

This library adds three jQuery plugin methods, the main entry point being the validate method:

Custom selectors

This library also extends jQuery with three custom selectors:

Validation event

The goal of these interactions is to provide feedback as early as possible, whilst avoiding user annoyance.

Displaying error messages before the user had the chance to even type something is not helpful.

  • By default, forms are validated on submit, triggered by the user clicking the submit button or pressing enter when a form input is focused (option onsubmit).
  • In addition, once a field was highlighted as being invalid, it is validated whenever the user types something in the field (option onkeyup).
  • When the user enters something invalid into a valid field, it is also validated when the field loses focus (option onfocusout).

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.

There are a few static methods on the validator object:

  

Error messages

An error message displays a hint for the user about invalid elements, and what is wrong.

There are four ways to provide error messages.

  • Via the title attribute of the input element to validate
  • via data attributes,
  • via error labels
  • via plugin settings (option messages).

All validation rules included here provide a default error message which you can use for prototyping,because it is used when no specific message is provided.

The priorities are as follows:

  • A custom message (passed by plugin options),
  • the element's title,
  • the default message.

When using data attributes, you can set a generic message for all rules, or specific messages per rule:

<input required data-msg="Please fill this field">
<input data-rule-minlength="2" data-rule-maxlength="4" data-msg-minlength="At least two chars" data-msg-maxlength="At most fours chars">

 

Error message display

Error messages are handled via label elements with an additional class (option errorClass).

The link between the message and the invalid element is provided via the labels for attribute.

When provided in the markup, they are shown and hidden accordingly, and otherwise created on demand.

By default, labels are created after the invalid element, this is also customizable (option errorPlacement).

It is also possible to put them into an error container (option errorLabelContainer).

To use a different element then a label, specify the errorElement option.

General messages

In addition to field-specific messages you can display a general "your form is invalid, please fix the highlighted fields!" message in a container anywhere on your page,

eg. above the form (option errorContainer).

The container is shown and hidden when errors occur and are fixed accordingly.

The container for error labels (option errorLabelContainer) can also be nested inside the error container.

Focusing of invalid elements

By default, the first invalid element in a form is focused after submitting a form with invalid elements.

To prevent confusion on the behalf of the user, the plugin remembers the element that had focus when the form was submitted, and refocuses that element.

That way the user can try to fill out elements of the form at the end, without being forced to focus them again and again. This can be disabled (option focusInvalid).

 

General Guidelines

provides detailed discussion of the design and ideas behind the plugin,

explaining why certain things are as they are.

It covers the features in more detail than the API documentation, which just briefly explains the various methods and options available.

Fields with complex names (brackets, dots)

When you have a name attribute like user[name], make sure to put the name in quotes.

More details in the General Guidelines.

If your form consists of fields using names that aren't legal JavaScript identifiers, you have to quote those names when using the rules option:

 $("#myform").validate({
rules: {
// no quoting necessary
name: "required",
// quoting necessary!
"user[email]": "email",
// dots need quoting, too!
"user.address.street": "required"
}
});

  

Too much recursion

Another common problem occurs with this code:

$("#myform").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
$(form).submit();
}
});

This results in a too-much-recursion error:

$(form).submit() triggers another round of validation, resulting in another call to submitHandler, and voila, recursion.

Replace that with form.submit(), which triggers the native submit event instead and not the validation.

So the correct code looks slightly different:

 $("#myform").validate({
submitHandler: function(form) {
form.submit();
}
});

 

Form submit

By default, the form submission is prevented when the form is invalid, and submitted as normal when it is valid. You can also handle the submission manually (option submitHandler).

Skipping validation on submit

To skip validation while still using a submit-button, add the attribte "formnovalidate" to that input:

 <input type="submit" name="go" value="Submit">
<input type="submit" formnovalidate name="cancel" value="Cancel">

This used to work by adding class="cancel" to the input, this is now deprecated.  

Demo for the cancel button

Developing and debugging a form

While developing and debugging the form, you should set the debug option to true.

That prevents form submission on both valid and invalid forms and outputs some helpful messages to window.console (available via Firebug or Firebug Lite) that help debugging

When you have everything set up and don't get any error messages displayed, check if your rules all accept empty elements as valid (like email or url methods).

Some issues are caused by certain form element's names.

  • A name you should avoid is "submit" (for submit buttons and anything else).

    • browsers expose form elements as properties of the form element, by their name, in this case hiding native methods like submit(). 
    • Just don't use name="submit" and you're good.

Validating multiple forms on one page

The plugin can handle only one form per call.

In case you have multiple forms on a single page which you want to validate, you have to initialise them all individually:

$( "form" ).each( function() {
$( this ).validate( options );
} );

You can avoid having to duplicate the plugin settings by modifying the defaults, using jQuery.validator.setDefaults to override multiple settings at once. 

 

目标:

The ultimate goal of this plugin is to make working with forms more fun for everyone.

By improving the interaction, it is easier and less annoying for the user to fill out the form and submit it.

To achieve this, it is important that the plugin is actually deployed on websites around the world,

so a lot of focus is spent on making it easy for developers – that's you – to use the plugin.

The plugin can never replace serverside validation and doesn't intend to do so.

Having both in place gives you the necessary security for your application, as well as improved usability.

使用建议

  • Mandated: A 'name' attribute is required for all input elements needing validation, and the plugin will not work without this.

    • A 'name' attribute must also be unique to the form, as this is how the plugin keeps track of all input elements.
    • However, each group of radio or checkbox elements will share the same 'name' since the value of this grouping represents a single piece of the form data.
  • Optionally: Each input can have a label associated with it, where the 'for' attribute of the label refers to the 'id' attribute of the input.
    • It's also a common practice to have 'id' and 'name' attributes with the same value, although keep in mind that since this plugin does not use the 'id' attribute, this is not mandatory.
<label for="firstname">Firstname</label>
<input id="firstname" name="fname">

  

jQuery validator plugin之概要的更多相关文章

  1. jQuery validator plugin 之 custom methods 案例1:multi email

    1.add method jQuery.validator.addMethod( "multiemail", function (value, element) { var ema ...

  2. jQuery validator plugin之Validator

    Validator.destroy() Destroys this instance of validator freeing up resources and unregistering event ...

  3. jQuery validator plugin之Methods

    step method Makes the element require a given step. step( value ) value Type: Number Step value requ ...

  4. jQuery validator plugin之Plugin Method

    原文 .validate() validate( [options ] ) options Type: Object debug (default: false) Type: Boolean Enab ...

  5. jQuery validator plugin之Selector

    原文 :unchecked Selector Selects all elements that are unchecked. jQuery( ":unchecked" ) Inv ...

  6. jQuery.validator 详解二

    前言:上一篇详细的介绍了jQuery.validator( 版本v1.13.0 )的验证规则,这一篇重点讲述它的源码结构,及如何来对元素进行验证,错误消息提示的内部实现 一.插件结构(组织方式) 在讲 ...

  7. jQuery.validator 详解

    jQuery.validator 详解二 前言:上一篇详细的介绍了jQuery.validator( 版本v1.13.0 )的验证规则,这一篇重点讲述它的源码结构,及如何来对元素进行验证,错误消息提示 ...

  8. jQuery Validation Plugin学习

    http://blog.csdn.net/violet_day/article/details/14109261 jQuery Validation Plugin Demo 一.默认校验规则 (1)r ...

  9. (转)jquery.validator规则

      登录|注册     收藏成功 确定 收藏失败,请重新收藏 确定 标题 标题不能为空 网址 标签 摘要   公开 取消收藏             分享资讯 传PPT/文档 提问题 写博客 传资源 ...

随机推荐

  1. linux的基本操作(正则表达式)

    正则表达式 这部分内容可以说是学习shell脚本之前必学的内容.如果你这部分内容学的越好,那么你的shell脚本编写能力就会越强.所以不要嫌这部分内容啰嗦,也不要怕麻烦,要用心学习.一定要多加练习,练 ...

  2. Python学习之旅(三十五)

    Python基础知识(34):电子邮件(Ⅰ) 几乎所有的编程语言都支持发送和接收电子邮件 在使用Python收发邮件前,请先准备好至少两个电子邮件,如xxx@163.com,xxx@sina.com, ...

  3. Selenium 2(Webdriver)

    如何用webdriver打开一个浏览器,我们常用的浏览器有firefox和IE两种,firefox是selenium支持得比较成熟的浏览器,很多新的特性都会在firefox中体现.但是做页面的测试,启 ...

  4. vsftp快速搭建ftp服务器

    什么是vsftp: vsftpd 是一个 UNIX 类操作系统上运行的服务器的名字,它可以运行在诸如 Linux, BSD, Solaris, HP-UX 以及 IRIX 上面.它支持很多其他的 FT ...

  5. XP支持AHCI硬盘工作模式

    故障 装XP系统后开启AHCI模式会出现开机蓝屏重启的问题,如何在XP下加载AHCI驱动,以便开启BIOS中AHCI选项来发挥硬盘的最佳性能. 问题分析XP系统无法直接支持AHCI硬盘高速模式,需要加 ...

  6. linux 通过pid 寻找程序路径的最简单命令(pwdx)

    在linux实际操作命令中,查看pid的方式有很多种,通过pid找程序路径的方式也有好几个,但是可能大家都忽略的一个很简单也是很实用的命令:pwdx. 比如要查找某个java编写的程序运行情况可通过j ...

  7. [js]this关键字代表当前执行的主体

    点前是谁,this就是谁 <div id="div1" class="div1"></div> <div id="div ...

  8. Go 初体验 - 令人惊叹的语法 - defer.3 - defer 函数参数计算时机

    defer 函数的参数计算时机 定义一个 defer 函数,接收参数 n: 调用: 输出: 有点惊讶,为什么不是 100 200 200? go 语言里,defer 函数的参数是在定义位置被计算的,也 ...

  9. ADB工具的使用

    ADB即Android Debug Bridge调试桥,可以用来调试管理Android设备与设备模拟器的状态,比如,在Android设备上运行Shell,在电脑和设备之间互传文件... 那么问题来了. ...

  10. ASP.NET MVC案例教程(三)

    ASP.NET MVC案例教程(二) 让第一个页面跑起来 现在,我们来实现公告系统中的第一个页面——首页.它非常简单,只包括所有公告分类的列表,并且每个列表项是一个超链接.其中分类数据是用我们的Moc ...