jquery.validate.js 详解

jquery下载地址:https://jquery.com/download/

jquery.validate.js下载地址:https://cdnjs.com/libraries/jquery-validate

jquery.validate.js是我们经常用到的form表单验证插件,可以很方便的帮我们进行表单验证。这里来学习一下他的用法,觉得不够详细的同学,可以去官网继续学习。

1.jquery.validate.js依赖于jquery,在页面引入jquery.validate.js前一定要先引入jquery。

<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript"  src="js/jquery.validate.js"></script>

2.使用jquery.validate.js进行验证,需要先对form表单进行规则添加,添加的方法为 .validate( [options ] ) ,可以调用.valid() 来获取验证结果。

1.validate( [options ] ) 制定规则

     1.1options

options类型默认值参数解释

debug 

booleanfalse 

启用调试模式。如果为true,则不提交表单,并在控制台上显示某些错误(检查Windows是否存在控制台属性)。如果要启用调式模式,需要在提交表单时将该属性置为false,而不是在验证完以后。

submitHandler function()native form submit

event:提交事件

form:当前被验证的form,作为一个元素返回。

用于在表单有效时处理实际提交的回调。设置该属性后,验证通过后将不会默认提交请求,而是执行该属性定义的方法。这里可以做一些请求预处理或者请求回调。

invalidHandlerfunction() 

event:自定义事件对象

validator:当前表单的验证结果

提交无效表单时的自定义代码回调。

ignore Selectorhidden 验证时要忽略的元素
rules object从标记(类、属性、数据)读取规则 定义自定义规则的键/值对。键是元素的名称(或一组复选框/单选按钮),值是由规则/参数对或纯字符串组成的对象。可以与类/属性/数据规则组合。每个规则都可以指定为具有依赖属性,以便仅在特定条件下应用该规则。
messagesobject 

 

定义自定义消息的键/值对。键是一个元素的名称,值是要为该元素显示的消息。可以使用另一个映射,其中包含每个规则的特定消息,而不是普通消息。重写元素的title属性或方法的默认消息(按该顺序)。每个消息可以是字符串或回调。回调在验证器的作用域中调用。
groupsobject  指定错误消息的分组。一个组由一个任意的组名作为键和一个以空格分隔的元素名列表作为值组成。使用errorPlacement控制组消息的放置位置。
normalizerfunction()  准备/转换要验证的元素值,这个方法只会将元素的值在验证前进行转换,并不会转换元素的初始值。eg:一个元素的值为a,该方法会将其转换为b进行验证,但最终请求时传的参数值仍然是a。该属性也可以作用在单个元素上,作用域取决于他的位置。
onsubmit booleantrue

event

element

是否在提交前验证,默认为true。如果改为false,那么可以去除提交前的验证,想什么时候验证什么时候验证。
onfocusoutboolean/function() 

event

element

失去焦点验证。可以将该值设置为false或者一个function。true无效。
onkeyupboolean/function() 

event

element

是否在敲击键盘时验证。可以将该值设置为false或者一个function。true无效。
onclickboolean/function() 

event

element

是否在点击时验证。可以将该值设置为false或者一个function。true无效。
focusInvalid booleantrue 当该值为true时,提交表单后,如果有一个元素拥有焦点,那么焦点仍然处于该元素;否则,第一个未通过验证的元素将获得焦点。
focusCleanup booleanfalse 当一个错误的元素获取到焦点时,移除他的错误属性,避免与focusInvalid组合使用。
errorClass Stringerror 使用此类创建错误标签,查找现有错误标签并将其添加到无效元素中。
validClass Stringvalid 为验证成功的元素添加属性
errorElement Stringlabel 指定创建错误信息的元素,默认时label。label的好处在于清晰的展示错误信息和错误元素的关系。
wrapper Stringwindow 用指定的元素包装错误标签。与errorLabelContainer结合使用可创建错误消息列表
errorLabelContainerSelector  指定展示wrapper过的错误信息的元素。
errorContainerSelector  指定需要展示的errorLabelContainer
showErrorsfunction() 

errorMap

errorList

自定义消息显示处理程序。参数只包含当前已验证的那些元素,在对focusout或keyup进行验证时,这些元素可以是单个元素。通过调用this.defaultShowErrors()来触发(除了您自己的消息之外)默认行为。
errorPlacementfunction()默认追加在验证的元素后面

error:错误的label

element:验证的元素

自定义错误信息的添加位置
successString/function()  为成功的元素添加class,或者指定成功的label
highlightfunction()errorClass添加到错误的元素上

element

errorClass

validClass

为错误的元素添加errorClass
unhighlightfunction()将错误的元素上的errorClass移除 将错误的元素上的errorClass移除
ignoreTitlebooleanfalse 设置为跳过从title属性读取消息,有助于避免Google工具栏出现问题;默认值为false表示兼容性,title中的消息很可能在将来的版本中被完全删除。

    1.2 rules 默认可用的规则(additional-methods.js 提供了更多的方法)

options类型注释
requiredboolean是否必填
emailboolean是否输入正确的email格式
urlboolean是否输入正确的url格式
dateboolean是否输入正确的日期格式
dateISOboolean是否输入正确的ISO日期格式
numberboolean是否输入正确的数字
digitsboolean是否输入正确的自然数(0,1,2,3,4....)
equalToselector是否和selector的值相同
acceptString是否输入合法后缀名的字符串
maxlengthnumber最大长度
minlengthnumber最小长度
rangelength[0,5]长度在[0,5]内
maxnumber最大值
minnumber最小值
range[0,5]大小在[0,5]内
remoteobject  return:boolean异步检查输入的值是否符合要求
stepnumber是否输入给定的数字step

1.3 使用示例:

1.debug

$("#myform").validate({
        debug: true
});

2.submitHandler 

改为ajax提交:
$("#myform").validate({
        submitHandler: function(form) {
                        $(form).ajaxSubmit();
        }
});

默认提交预处理:
$("#myform").validate({
          submitHandler: function(form) {
                            //在这里添加请求预处理
                            form.submit();
          }
});

3.invalidHandler

$("#myform").validate({
        invalidHandler: function(event, validator) {
                        // 'this' 代表当前的form
                        var errors = validator.numberOfInvalids();
                        if (errors) {
                            $("div.error span").html("失效字段有"+errors +"个");
                            $("div.error").show();
                        } else {
                            $("div.error").hide();
                        }
         }
});

4.ignore 

忽略所有被class ‘ignore修修饰的元素

$("#myform").validate({
        ignore: ".ignore"
});

5.rules

1.简单的规则:
$("#myform").validate({
        rules: {
            // 这里可以使用字符串"required",也可以使用{required:true}
            name: "required",
            // 组合规则。
            email: {
                required: true,
                //符合email规则
                email: true
             }
         }
});

2.依赖规则
$("#myform").validate({
  rules: {
    contact: {
      required: true,
      //是否是email地址决定于元素contactform_email是否被选择
      email: {
        depends: function(element) {
          return $("#contactform_email").is(":checked");
        }
      }
    }
  }
});

3.当元素bonus-material被选择时,那么元素pay_what_you_want的值最小为15
$("#myform").validate({
  rules: {
    pay_what_you_want: {
      required: true
      min: {
        param: 15,
        depends: function(element) {
          return $("#bonus-material").is(":checked");
        }
      }
    }
  }
});

6.messages

1.简单的message
$("#myform").validate({
  rules: {
    name: "required",
    email: {
      required: true,
      email: true
    }
  },
  messages: {
    //name没有填时展示的信息
    name: "Please specify your name",
    email: {
      //email没有填时展示的信息
      required: "We need your email address to contact you",
      //email违规时展示的信息
      email: "Your email address must be in the format of name@domain.com"
    }
  }
});

2.带参的message
$("#myform").validate({
  rules: {
    name: {
      required: true,
      minlength: 2
    }
  },
  messages: {
    name: {
      required: "We need your email address to contact you",
      //name长度不够时展示的消息,这里的{0}代表rules中的minlength的值
      minlength: jQuery.validator.format("At least {0} characters required!")
    }
  }
});

7.groups

对表单使用表布局,在输入后的下一个单元格中放置错误消息。
$("#myform").validate({
  groups: {
    //创建一个组名为username的组,该组可以控制元素名为fname,lname的元素
    username: "fname lname"
  },
  errorPlacement: function(error, element) {
    //一旦元素名称为fname或者lname,那么将错误信息添加到元素id为lastname的元素后面
    if (element.attr("name") == "fname" || element.attr("name") == "lname" ) {
      error.insertAfter("#lastname");
    } else {
     //否则添加到错误元素后面
      error.insertAfter(element);
    }
  }
});

8.normalizer

1.将值进行trim处理

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Makes "field" required and use a normalizer to trim its value before validating</title>
<link rel="stylesheet" href="https://jqueryvalidation.org/files/demo/site-demos.css">
 
</head>
<body>
<form id="myform">
<label for="field">Required: </label>
<input class="left" id="field" name="field">
<br/>
<input type="submit" value="Validate!">
</form>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
  debug: true,
  success: "valid"
});
$( "#myform" ).validate( {
	 submitHandler :function(form){
		 var d = {};
		     alert(JSON.stringify($(form).serializeArray()));
	 },
  rules: {
    field: {
      required: true,
      normalizer: function( value ) {
        // Trim the value of the `field` element before
        // validating. this trims only the value passed
        // to the attached validators, not the value of
        // the element itself.
        return $.trim( value );
      }
    }
  }
} );
</script>
</body>
</html>

2.

9.errorClass 

使用invalid作为错误的class
$("#myform").validate({
  errorClass: "invalid"
});

10.validClass 

为所有通过验证的元素添加success属性
$("#myform").validate({
  validClass: "success"
});

11.wrapper,errorLabelContainer

将错误的信息用li封装成一个无序的列表,并展示在id为messageBox的元素中。
$("#myform").validate({
  errorLabelContainer: "#messageBox",
  wrapper: "li",
  submitHandler: function() { alert("Submitted!") }
});

12.errorContainer

将错误的信息用li封装成一个无序的列表,并展示在id为messageBox的元素中。
展示messageBox1和messageBox2的错误内容
$("#myform").validate({
  errorContainer: "#messageBox1, #messageBox2",
  errorLabelContainer: "#messageBox1 ul",
  wrapper: "li", debug:true,
  submitHandler: function() { alert("Submitted!") }
});

13.showErrors

$("#myform").validate({
  showErrors: function(errorMap, errorList) {
    $("#summary").html("Your form contains "
      + this.numberOfInvalids()
      + " errors, see details below.");
    this.defaultShowErrors();
  }
});

14.errorPlacement

$("#myform").validate({
  errorPlacement: function(error, element) {
    //将封装错误信息的label追加到元素父节点中的第一个td后面的td中
    error.appendTo( element.parent("td").next("td") );
  }
});

15.success

1.将验证通过的元素的class添加valid
$("#myform").validate({
  success: "valid",
  submitHandler: function() { alert("Submitted!") }
});

2.创建一个class为valid的label,并且将内容设置位"ok!"
$("#myform").validate({
  success: function(label) {
    label.addClass("valid").text("Ok!")
  },
  submitHandler: function() { alert("Submitted!") }
});

16.highlight,unhighlight

1.将错误的元素添加闪烁效果
$("#myform").validate({
  highlight: function(element, errorClass) {
    $(element).fadeOut(function() {
      $(element).fadeIn();
    });
  }
});

2.当验证错误时将错误的元素添加errorClass,移除validClass,并将form下该元素ID的label添加errorClass;当验证成功时,将元素移除errorClass,添加validClass,并将form下该元素ID的label移除errorClass。

$("#myform").validate({
  highlight: function(element, errorClass, validClass) {
    $(element).addClass(errorClass).removeClass(validClass);
    $(element.form).find("label[for=" + element.id + "]")
      .addClass(errorClass);
  },
  unhighlight: function(element, errorClass, validClass) {
    $(element).removeClass(errorClass).addClass(validClass);
    $(element.form).find("label[for=" + element.id + "]")
      .removeClass(errorClass);
  }
});

17.ignoreTitle

配置插件以在查找消息时忽略已验证元素的标题属性。
$("#myform").validate({
  ignoreTitle: true
});

18.remote

1.从地址check-email.php来检查是否通过
$( "#myform" ).validate({
  rules: {
    email: {
      required: true,
      email: true,
      remote: "check-email.php"
    }
  }
});

2.通过post方法从check-email.php检查是否通过,参数为data
$( "#myform" ).validate({
  rules: {
    email: {
      required: true,
      email: true,
      remote: {
        url: "check-email.php",
        type: "post",
        data: {
          username: function() {
            return $( "#username" ).val();
          }
        }
      }
    }
  }
});

 

2.valid() 验证规则

 $("#myForm").valid()。返回boolean,表示验证是否通过。

3.rules() 对一个元素查看,添加,移除规则。

1.查看规则

console.log($("#field").rules().toString());

控制台:{"required":true}

2.添加规则

$( "#myinput" ).rules( "add", {
  minlength: 2
});

$( "#myinput" ).rules( "add", {
  required: true,
  minlength: 2,
  messages: {
    required: "Required input",
    minlength: jQuery.validator.format("Please, at least {0} characters are necessary")
  }
});

3.移除规则

$( "#myinput" ).rules( "remove" );

$( "#myinput" ).rules( "remove", "min max" );

4.Validator

validate方法返回一个Validator对象,这个对象提供了一些方法供我们使用,学会这些方法可以更灵活的使用这个插件。

4.1 私有方法

方法参数返回值描述

Validator.form()

 boolean验证表单元素并返回true/false。

Validator.element(element )

element boolean验证某个元素是否符合规则

Validator.resetForm()

  重置表单

Validator.showErrors(errors )

object:包含键值对的json。键代表元素名称,值代表自定义的信息。

 展示自定义的错误信息
Validator.numberOfInvalids() number返回未通过验证的元素个数
Validator.destroy()  销毁这个Validator实例,释放资源,并且移除已注册的事件。

用法:

添加并展示自定义的错误信息。
var validator = $( "#myshowErrors" ).validate();
validator.showErrors({
  "firstname": "I know that your firstname is Pete, Pete!"
});

展示未通过的fields
var validator = $( "#myform" ).validate({
  invalidHandler: function() {
    $( "#summary" ).text( validator.numberOfInvalids() + " field(s) are invalid" );
  }
});

4.2 静态方法

方法

参数

返回值

描述

jQuery.validator.addMethod( name,function(value, element, params), message  )

name 方法名

function 方法

value 待验证的值

element 待验证的元素

params 方法的参数

message 展示的错误信息

 

添加一个自定义的方法

jQuery.validator.format(template,param...)

template 模板

param...参数

 

创建一个模板,并将参数依次替换进模板中的{0},{1}...位置

jQuery.validator.setDefaults(options)

options: validate方法的options

 

修改默认设置

jQuery.validator.addClassRules(name, rules)

name 添加的class名称

rules 触发的规则

 设置一种class,将参数中的rules绑定到这个class上。将这个class修饰在某个元素上时,同时会为该元素设置对应的规则。

用法:

1.jQuery.validator.addMethod( name,function(value, element, params), message  )

1.添加一个domain方法,用来验证元素的值是否以http://mycorporatedomain.com开头,未通过验证的响应信息为Please specify the correct domain for your documents
jQuery.validator.addMethod("domain", function(value, element) {
  return this.optional(element) || /^http:\/\/mycorporatedomain.com/.test(value);
}, "Please specify the correct domain for your documents");

2.添加一个math方法,该方法接受两个参数,用来检查给定的值是否等于两个参数的和,未通过验证的响应信息为jQuery.validator.format("Please enter the correct value for {0} + {1}")
jQuery.validator.addMethod("math", function(value, element, params) {
  return this.optional(element) || value == params[0] + params[1];
}, jQuery.validator.format("Please enter the correct value for {0} + {1}"));

3.添加一个laxEmail方法,用来验证是否符合emal规则,未通过验证的响应信息为Please enter a valid email address.
jQuery.validator.addMethod("laxEmail", function(value, element) {
  // allow any non-whitespace characters as the host part
  return this.optional( element ) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@(?:\S{1,63})$/.test( value );
}, 'Please enter a valid email address.');

2.jQuery.validator.format(template,param...)

var template = jQuery.validator.format("{0} is not a valid value");
// later, results in 'abc is not a valid value'
alert(template("abc"));

3.jQuery.validator.addClassRules(name, rules)

1.设置一个绑定了规则{required: true, minlength: 2}的class,定义为name。
jQuery.validator.addClassRules("name", {
  required: true,
  minlength: 2
});

2.定义两个class
jQuery.validator.addClassRules({
  name: {
    required: true,
    minlength: 2
  },
  zip: {
    required: true,
    digits: true,
    minlength: 5,
    maxlength: 5
  }
});

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值