JQuery 验证插件validate的showErrors参数的使用

来源:互联网 发布:unity a 寻路算法源码 编辑:程序博客网 时间:2024/05/17 07:08

1.showErrors的定义

http://jqueryvalidation.org/validate   介绍了showErrors的定义。

showErrors
Type: Function()
A custom message display handler. Gets the map of errors as the first argument and an array of errors as the second, called in the context of the validator object. The arguments contain only those elements currently validated, which can be a single element when doing validation onblur/keyup. You can trigger (in addition to your own messages) the default behaviour by calling this.defaultShowErrors().

Example: Update the number of invalid elements each time an error is displayed. Delegates to the default implementation for the actual error display.

1
2
3
4
5
6
7
8
$(".selector").validate({
showErrors: function(errorMap, errorList) {
$("#summary").html("Your form contains "
+ this.numberOfInvalids()
+ " errors, see details below.");
this.defaultShowErrors();
}
});

The callback gets passed two arguments:

  • errorMap
    Type: Object
    Key/value pairs, where the key refers to the name of an input field, values the message to be displayed for that input.
  • errorList
    Type: Array
    An array for all currently validated elements. Contains objects with the following two properties:
    • message
      Type: String
      The message to be displayed for an input.
    • element
      Type: Element
      The DOMElement for this entry.

2.使用

这里参数一errorMap是一个该函数被调用时传入的key/value对,即一个对象。这里就涉及到了如何访问这个对象的"key",与 "value"。
下面这段代码演示了如何在JS中访问key与value。
    var a = {          a:1,          b:2      };      for(var b in a){          alert(b + ":" + a[b]);      }  
遍历对象a,每次方位到key即变量b,而访问value则通过a[b],或者a.b。这样这个errorMap就可以访问了。

errorMap定义描述了,这里的key代表这输入域(可以是一个input控件)的name属性的值,而values则是这个控件需要显示的错误提示。现以下面这段代码为例。
    rules:{          'biz_loan_info_extLists[0].carBrand':{              required:true,              rangelength:[1,30]          }      },      messages:{           'biz_loan_info_extLists[0].carBrand':{               required:'汽车品牌型号不能为空,且长度范围1至30个字符',               rangelength:'输入应为1-30个字符'           }      }  
当validate验证失败时,其name即key,就是rules中定义需要验证的控件的name,上述代码为biz_loan_info_extLists[0].carBrand,而value就是其对应的message部分。例如当没有提供输入时,message为required部分,即'汽车品牌型号不能为空,且长度范围1至30个字符'。当输入字符长度不在1-30这个范围内时,提示输入应为1-30个字符。

定义完上述内容,就该使用showErrors函数在我指定的位置显示错误提示信息了,代码如下。
    showErrors:function(errorMap,errorList){          for(var prop in errorMap){              $("[name="+"'"+prop+"'"+"]").next(".help-block").text(errorMap[prop]);          }      }  
这里prop为key,由于prop为一个变量,因此需要在使用 单引号(')。这样即就完成了自定义的消息显示。
0 0