相信大家在做WEB前台开发时候,经常会有表单各种验证的小需求,今天就在这里总结哈jQuery实现表单验证的过程,具体步骤如下:

一、需要在前台页面引入jquery.js和jquery.validate.js两个js配置文件,两个js文件可以从官网进行下载或者直接百度查找。

二、前台页面需要有相应的表单信息,即就是form表单和表单内相应的需要验证的信息,如(在这里简单举例说明):

<form action="" id="myForm">
姓名:<input type="text" name="name" title="不能为空,并且长度在2到4之间">
密码:<input type="password" name="pwd" id="pwd" title="不能为空,并且长度在6到8之间">
重复密码:<input type="password" name=rePwd title="必须等于上一次输入的密码"> 
性别:
<div>
<input type="radio" name="sex">男<input type="radio" name="sex">女<br>
<label style="display:none" for="sex" class="error">必须选择性别</label>    //显示错误提示信息(使用jQuery表单验证显示错误提示信息会影响页面效果)
</div>
联系电话:<input type="text" name="phone" title="必须为11为数字,并且第一位数字为1">
年龄:<input type="text" name="age" title="年龄必须在18到58之间">
电子邮箱:<input type="text" name="email" title="不能为空">
......................................
</form>

三、使用jQuery进行表单验证,分为利用jquery.validate.js文件中有的验证规则进行验证和自定义验证规则进行验证:

// 很明显可以看得出来validate方法中存放的就是json格式(以key:value形式存放)的数据
$("#myForm").validate({
// 验证规则
rules:{
name:{
required:true,
rangelength:[2,4]
},
pwd:{
required:true,
rangelength:[6,8]
},
rePwd:{
required:true,
equalTo:"#pwd"
},
sex:"required",
phone:{
required:true,
//自定义验证规则,phoneRule为自定义验证规则的方法名
phoneRule:true
},
age:{
required:true,
range:[18,58]
},
email:{
required:true,
email:true
}
},
// 错误提示信息
messages:{

name:{
// 会默认转换为label标签展示到页面上
required:"姓名不能为空",
rangelength:"姓名的长度在2到4之间"
},
pwd:{
required:"密码不能为空",
rangelength:"长度在6到8之间"
},
rePwd:{
required:"不能为空",
equalTo:"必须等于第一次输入的密码"
}.
phone:{
required:"联系电话不能为空",
phoneRule:"联系电话书写不规范"
},
age:{
required:"年龄不能为空",
range:"年龄为18到58之间"
},
email:{
required:"电子邮箱不能为空",
email:"邮箱书写不规范"
}
}
});
// 自定义验证规则:phoneRule为验证的方法名;function(value,dom,param)为方法体,其中value为元素的值,dom为元素体本身,param为参数
$.validator.addMethod("phoneRule",function(value,dom,param){
// 使用一般方法
/*if(value.substring(0,1) != "1"){
return false;
}
if(value.length != 11){
return false;
}
return true;*/
// 使用正则表达式
var pattern = /^1[0-9]{10}$/;
var flag  = pattern.test(value);
return flag;
});

四、到这里一个jQuery对表单的验证基本就结束了,只要对JS、jQuery、json足够熟悉,完成一个复杂的表单验证也不是难事!