JS验证(网页设计中表单数据的验证)

本文介绍了一种使用JavaScript实现的表单数据验证方法,包括邮箱、电话、日期等常见字段的验证规则,并提供了一个名为Validator.js的验证库。该库包含了多种验证方法,如限制输入长度、日期格式、自定义正则表达式等,同时支持错误提示和处理。通过在HTML表单中设置dataType和msg属性,可以轻松地进行表单验证。

/***************************************************************************************************************************************************************************************

把以下2个文件放在同一目录下,在浏览器中打开demo.html即可

***************************************************************************************************************************************************************************************/

 
//文件Validator.js

Validator={
 Require : /.+/,
 Email : /^/w+([-+.]/w+)*@/w+([-.]//w+)*/./w+([-.]/w+)*$/,
 Phone : /^((/(/d{3}/))|(/d{3}/-))?(/(0/d{2,3}/)|0/d{2,3}-)?[1-9]/d{6,7}$/,
 Mobile : /^((/(/d{3}/))|(/d{3}/-))?13/d{9}$/,
 Url : /^http:////[A-Za-z0-9]+/.[A-Za-z0-9]+[//=/?%/-&_~`@[/]/':+!]*([^<>/"/"])*$/,
 IdCard : /^/d{15}(/d{2}[A-Za-z0-9])?$/,
 Currency : /^/d+(/./d+)?$/,
 Number : /^/d+$/,
 Zip : /^[1-9]/d{5}$/,
 QQ : /^[1-9]/d{4,8}$/,
 Integer : /^[-/+]?/d+$/,
 Double : /^[-/+]?/d+(/./d+)?$/,
 English : /^[A-Za-z]+$/,
 Chinese :  /^[/u0391-/uFFE5]+$/,
 UnSafe : /^(([A-Z]*|[a-z]*|/d*|[-_/~!@#/$%/^&/*/./(/)/[/]/{/}<>/?/////'/"]*)|.{0,5})$|/s/,
 IsSafe : function(str){return !this.UnSafe.test(str);},
 SafeString : "this.IsSafe(value)",
 Limit : "this.limit(value.length,getAttribute('min'),  getAttribute('max'))",
 LimitB : "this.limit(this.LenB(value), getAttribute('min'), getAttribute('max'))",
 Date : "this.IsDate(value, getAttribute('min'), getAttribute('format'))",
 Repeat : "value == document.getElementsByName(getAttribute('to'))[0].value",
 Range : "parseInt(getAttribute('min')) < value && value < parseInt(getAttribute('max'))",
 Compare : "this.compare(value,getAttribute('operator'),getAttribute('to'))",
 Custom : "this.Exec(value, getAttribute('regexp'))",
 Group : "this.MustChecked(getAttribute('name'), getAttribute('min'), getAttribute('max'))",
 ErrorItem : [document.forms[0]],
 ErrorMessage : ["The cause of failure as below : /t/t/t/t"],
 Validate : function(theform, mode){
  var obj = theform || event.srcElement;
  var count = obj.elements.length;
  this.ErrorMessage.length = 1;
  this.ErrorItem.length = 1;
  this.ErrorItem[0] = obj;
  for(var i=0;i<count;i++){
   with(obj.elements[i]){
    var _dataType = getAttribute("dataType");
    if(typeof(_dataType) == "object" || typeof(this[_dataType]) == "undefined")  continue;
    this.ClearState(obj.elements[i]);
    if(getAttribute("require") == "false" && value == "") continue;
    switch(_dataType){
     case "Date" :
     case "Repeat" :
     case "Range" :
     case "Compare" :
     case "Custom" :
     case "Group" :
     case "Limit" :
     case "LimitB" :
     case "SafeString" :
      if(!eval(this[_dataType])) {
       this.AddError(i, getAttribute("msg"));
      }
      break;
     default :
      if(!this[_dataType].test(value)){
       this.AddError(i, getAttribute("msg"));
      }
      break;
    }
   }
  }
  if(this.ErrorMessage.length > 1){
   mode = mode || 1;
   var errCount = this.ErrorItem.length;
   switch(mode){
   case 2 :
    for(var i=1;i<errCount;i++)
     this.ErrorItem[i].style.color = "red";
   case 1 :
    alert(this.ErrorMessage.join("/n"));
    this.ErrorItem[1].focus();
    break;
   case 3 :
    for(var i=1;i<errCount;i++){
    try{
     var span = document.createElement("SPAN");
     span.id = "__ErrorMessagePanel";
     span.style.color = "red";
     this.ErrorItem[i].parentNode.appendChild(span);
     span.innerHTML = this.ErrorMessage[i].replace(//d+:/,"*");
     }
     catch(e){alert(e.description);}
    }
    this.ErrorItem[1].focus();
    break;
   default :
    alert(this.ErrorMessage.join("/n"));
    break;
   }
   return false;
  }
  return true;
 },
 limit : function(len,min, max){
  min = min || 0;
  max = max || Number.MAX_VALUE;
  return min <= len && len <= max;
 },
 LenB : function(str){
  return str.replace(/[^/x00-/xff]/g,"**").length;
 },
 ClearState : function(elem){
  with(elem){
   if(style.color == "red")
    style.color = "";
   var lastNode = parentNode.childNodes[parentNode.childNodes.length-1];
   if(lastNode.id == "__ErrorMessagePanel")
    parentNode.removeChild(lastNode);
  }
 },
 AddError : function(index, str){
  this.ErrorItem[this.ErrorItem.length] = this.ErrorItem[0].elements[index];
  this.ErrorMessage[this.ErrorMessage.length] = this.ErrorMessage.length + ":" + str;
 },
 Exec : function(op, reg){
  return new RegExp(reg,"g").test(op);
 },
 compare : function(op1,operator,op2){
  switch (operator) {
   case "NotEqual":
    return (op1 != op2);
   case "GreaterThan":
    return (op1 > op2);
   case "GreaterThanEqual":
    return (op1 >= op2);
   case "LessThan":
    return (op1 < op2);
   case "LessThanEqual":
    return (op1 <= op2);
   default:
    return (op1 == op2);           
  }
 },
 MustChecked : function(name, min, max){
  var groups = document.getElementsByName(name);
  var hasChecked = 0;
  min = min || 1;
  max = max || groups.length;
  for(var i=groups.length-1;i>=0;i--)
   if(groups[i].checked) hasChecked++;
  return min <= hasChecked && hasChecked <= max;
 },
 IsDate : function(op, formatString){
  formatString = formatString || "ymd";
  var m, year, month, day;
  switch(formatString){
   case "ymd" :
    m = op.match(new RegExp("^//s*((
//d{4})|(//d{2}))([-./])(//d{1,2})//4(//d{1,2})//s*$"));
    if(m == null ) return false;
    day = m[6];
    month = m[5]--;
    year =  (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10));
    break;
   case "dmy" :
    m = op.match(new RegExp("^//s*(
//d{1,2})([-./])(//d{1,2})//2((//d{4})|(//d{2}))//s*$"));
    if(m == null ) return false;
    day = m[1];
    month = m[3]--;
    year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10));
    break;
   default :
    break;
  }
  var date = new Date(year, month, day);
        return (typeof(date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate());
  function GetFullYear(y){return ((y<30 ? "20" : "19") + y)|0;}
 }
 }


//文件 demo.html  

//该文件只是举例说明如何使用 Validator.js文件 


<! DOCTYPE html PUBLIC "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd" >
< html >
< head >< title ></ title >
  
< meta  http-equiv ="Content-Type"  content ="text/html; charset=gb2312" >
< meta  http-equiv ="Content-Language"  content ="gb2312" >   
< script  language ="javascript"  type ="text/javascript"  src ="Validator.js" ></ script >
</ head >
< body >
< title > 表单验证类 Validator v1.05 </ title >
 
< style >
 body,td
{font:normal 12px Verdana;color:#333333}
 input,textarea,select,td
{font:normal 12px Verdana;color:#333333;border:1px solid #999999;background:#ffffff}
 table
{border-collapse:collapse;}
 td
{padding:3px}
 input
{height:20;}
 textarea
{width:80%;height:50px;overflow:auto;}
 form
{display:inline}
 
</ style >
 
< table  align ="center" >
  
< form  name ="theform"  id ="demo"  method ="get"  onSubmit ="return Validator.Validate(this,2)" >
  
< tr >
   
< td > 身份证号: </ td >< td >< input  name ="Card"  dataType ="IdCard"  msg ="身份证号错误" ></ td >
  
</ tr >
    
< tr >
   
< td > 真实姓名: </ td >< td >< input  name ="Name"  dataType ="Chinese"  msg ="真实姓名只允许中文" ></ td >
  
</ tr >
  
< tr >
   
< td > ID: </ td >< td >< input  name ="username"  dataType ="Username"  msg ="ID名不符合规定" ></ td >
  
</ tr >
  
< tr >
   
< td > 英文名: </ td >< td >< input  name ="Nick"  dataType ="English"  require ="false"  msg ="英文名只允许英文字母" ></ td >
  
</ tr >
    
< tr >
   
< td > 主页: </ td >< td >< input  name ="Homepage"  require ="false"  dataType ="Url"    msg ="非法的Url" ></ td >
  
</ tr >
  
< tr >
   
< td > 密码: </ td >< td >< input  name ="Password"  dataType ="SafeString"    msg ="密码不符合安全规则"  type ="password" ></ td >
  
</ tr >
  
< tr >
   
< td > 重复: </ td >< td >< input  name ="Repeat"  dataType ="Repeat"  to ="Password"  msg ="两次输入的密码不一致"  type ="password" ></ td >
  
</ tr >
  
< tr >
   
< td > 信箱: </ td >< td >< input  name ="Email"  dataType ="Email"  msg ="信箱格式不正确" ></ td >
  
</ tr >
    
< tr >
   
< td > 信箱: </ td >< td >< input  name ="Email"  dataType ="Repeat"  to ="Email"  msg ="两次输入的信箱不一致" ></ td >
  
</ tr >
  
< tr >
   
< td > QQ: </ td >< td >< input  name ="QQ"  require ="false"  dataType ="QQ"  msg ="QQ号码不存在" ></ td >
  
</ tr >
    
< tr >
   
< td > 身份证: </ td >< td >< input  name ="Card"  dataType ="IdCard"  msg ="身份证号码不正确" ></ td >
  
</ tr >
  
< tr >
   
< td > 年龄: </ td >< td >< input  name ="Year"  dataType ="Range"  msg ="年龄必须在18~28之间"  min ="18"  max ="28" ></ td >
  
</ tr >
   
< tr >
   
< td > 年龄1: </ td >< td >< input  name ="Year1"  require ="false"  dataType ="Compare"  msg ="年龄必须在18以上"  to ="18"  operator ="GreaterThanEqual" ></ td >
  
</ tr >
   
< tr >
   
< td > 电话: </ td >< td >< input  name ="Phone"  require ="false"  dataType ="Phone"  msg ="电话号码不正确" ></ td >
  
</ tr >
   
< tr >
   
< td > 手机: </ td >< td >< input  name ="Mobile"  require ="false"  dataType ="Mobile"  msg ="手机号码不正确" ></ td >
  
</ tr >
     
< tr >
   
< td > 生日: </ td >< td >< input  name ="Birthday"  dataType ="Date"  format ="ymd"  msg ="生日日期不存在" ></ td >
  
</ tr >
   
< tr >
   
< td > 邮政编码: </ td >< td >< input  name ="Zip"  dataType ="Custom"  regexp ="^[1-9]d{5}$"  msg ="邮政编码不存在" ></ td >
  
</ tr >
  
< tr >
   
< td > 邮政编码: </ td >< td >< input  name ="Zip1"  dataType ="Zip"  msg ="邮政编码不存在" ></ td >
  
</ tr >
  
< tr >
   
< td > 操作系统: </ td >< td >< select  name ="Operation"  dataType ="Require"   msg ="未选择所用操作系统"   >< option  value ="" > 选择您所用的操作系统 </ option >< option  value ="Win98" > Win98 </ option >< option  value ="Win2k" > Win2k </ option >< option  value ="WinXP" > WinXP </ option ></ select ></ td >
  
</ tr >
  
< tr >
   
< td > 所在省份: </ td >< td > 广东 < input  name ="Province"  value ="1"  type ="radio" > 陕西 < input  name ="Province"  value ="2"  type ="radio" > 浙江 < input  name ="Province"  value ="3"  type ="radio" > 江西 < input  name ="Province"  value ="4"  type ="radio"  dataType ="Group"   msg ="必须选定一个省份"   ></ td >
  
</ tr >
  
< tr >
   
< td > 爱好: </ td >< td > 运动 < input  name ="Favorite"  value ="1"  type ="checkbox" > 上网 < input  name ="Favorite"  value ="2"  type ="checkbox" > 听音乐 < input  name ="Favorite"  value ="3"  type ="checkbox" > 看书 < input  name ="Favorite"  value ="4"  type ="checkbox" " dataType ="Group"  min ="2"  max ="3"   msg ="必须选择2~3种爱好" ></ td >
  
</ tr >
   
< td > 自我介绍: </ td >< td >< textarea  name ="Description"  dataType ="Limit"  max ="10"   msg ="自我介绍内容必须在10个字之内" > 中文是一个字 </ textarea ></ td >
  
</ tr >
     
< td > 自传: </ td >< td >< textarea  name ="History"  dataType ="LimitB"  min ="3"  max ="10"   msg ="自传内容必须在[3,10]个字节之内" > 中文是两个字节t </ textarea ></ td >
  
</ tr >
    
< tr >
   
< td > 相片上传: </ td >< td >< input  name ="up"  dataType ="Filter"  msg ="非法的文件格式"  type ="file"  accept ="jpg, gif, png" ></ td >
  
</ tr >
  
< tr >
   
< td  colspan ="2" >< input  name ="Submit"  type ="submit"  value ="确定提交" >< input  onClick ="Validator.Validate(document.getElementById('demo'))"  value ="检验模式1"  type ="button" >< input  onClick ="Validator.Validate(document.getElementById('demo'),2)"  value ="检验模式2"  type ="button" >< input  onClick ="Validator.Validate(document.getElementById('demo'),3)"  value ="检验模式3"  type ="button" ></ td >
  
</ tr >
  
</ form >
 
</ table >
</ body >

</ html >

 

 

 

/***************************************************************************************************************************************************************************************

                                               
                                             帮助文档


********************************************************************************************

Validator.js文件中 方法(Methods)说明

********************************************************************************************


-------------------------------------------------------------------------------------------

为便于理解,这里参考C++的语法列出Volidator的方法原型。
提示:

--------------------------------------------------------------------------------------------

以Exec方法为例作说明。

static public bool Exec(string op, object reg)
static 表示静态方法,不需要实例化类即可用.语法使用。
public 表示公开方法,可用.语法使用。
bool 表示方法返回的类型为布尔值true或false。
string op 表示参数op为字符串型。
object reg 表示参数reg为对象型,这里是正则表达式对象。
另外,如果参数object reg表示为object reg="^.*$",则表示参数reg可选,在不指定reg参数时方法将按reg值为^.*$进行操作。如果bool改为void,则表示该方法无返回值。

--------------------------------------------------------------------------------------------
 
static public bool Validate(object theform=event.srcElement, int mode=1)
说明:Validator的主方法,测试表单theform是否符合验证要求,符合则返回true,否则以mode所指定的出错提示模式来提示错误。
应用:表单验证入口方法。
--------------------------------------------------------------------------------------------

static public bool limit(int len, int min=0, int max)
说明:测试输入字符的长度值len(字符数或字节数),是否在区间[min, max]。
应用:dataType属性值为Limit/LimitB时的验证。

--------------------------------------------------------------------------------------------

static public int LenB(string str)
说明:获取输入字符串的字节数。一个中文字为两个字节。
应用:dataType属性值为Limit/LimitB时的验证。

--------------------------------------------------------------------------------------------

static public void ClearState(object elem)
说明:清除指定表单项elem的错误提示信息。
应用:Validate方法


--------------------------------------------------------------------------------------------

static public void AddError(int index, string str)
说明:将未通过验证的表单项的当前索引值index和错误提示信息str添加到Validator的ErrorMessage和ErrorItem数组。
应用:Validate方法

--------------------------------------------------------------------------------------------

static public bool Exec(string op, object reg)
说明:测试字符串op是否符合正则对象reg所设定的规则,是则返回true,否则返回false。
应用:当dateType属性值为Custom时的验证

--------------------------------------------------------------------------------------------

static public bool compare(int op1, string operator, int op2)
说明:比较op1和op2是否符合operator所指定的关系,是则返回true,否则返回false。
应用:当dateType属性值为Compare时的验证

--------------------------------------------------------------------------------------------

static public bool IsSafe(string str)
说明:测试字符串str是否符合安全规则----包含字母、数字和特殊符号的一种以上,不允许出现空间,至少需要6位的长度。
应用:dataType属性值为SafeString时的验证。

--------------------------------------------------------------------------------------------

static public bool IsIdCard(string number)
说明:测试number是否符合身份证号码标准,是则返回true,否则返回false。
应用:当dateType属性值为IdCard时的验证。
注意:因为考虑到代码效率及体积的大小,只验证6位区域码的省份或直辖市(前2位)。

--------------------------------------------------------------------------------------------

static public bool IsDate(string op, string formatString)
说明:测试op是否符合formatString所指定的日期格式,是则返回true,否则返回false。
应用:当dateType属性值为Date时的验证。

--------------------------------------------------------------------------------------------

static public bool MustChecked(string name, int min=1, int max=*)
说明:测试名称为参数name所指定的单/多选按钮组的选中个数是否在[min, max]区间,是则返回true,否则返回false。
注意,对于单选按钮组,min和max属性没有意义,而对于多选按钮组,在不指定max值时,默认值为多选按钮组的多选按钮个数。
应用:当dateType属性值为Group时的验证

--------------------------------------------------------------------------------------------

static public bool DoFilter(string input, string filter)
说明:测试输入值 input 是否包含在 filter 所指定的列表,是则返回true,否则返回false。
应用:当dateType属性值为Filter时的验证,主要用于上传文件的限制过滤。

--------------------------------------------------------------------------------------------


********************************************************************************************

使用帮助(FAQs)

********************************************************************************************

-------------------------------------------------------------------------------------------

验证表单

在表单中加上onsubmit事件,触发调用Validaotor的Validate方法,代码示例:
<form onSubmit="return Validator.Validate(this,3)" action="your_application_page" method="post">
... ...
</form>
Validate方法有两个可选参数,第一个为表单对象,如果是写在表单的onsubmit事件中,可以用this指代当前表单,默认值为事件源对象;第二个参数为错误提示模式,可选值为1,2和3,默认值为1。省略第二个参数时相当于使用Validate(objform,1),省略第一个参数时相当于Validate(this,1)。注意,不可以省略第一个参数而只写第二个参数,Validate(,2)是错误的用法。

--------------------------------------------------------------------------------------------

验证输入是否Email地址

代码示例:
<input name="Email" dataType="Email" msg="信箱格式不正确">

<input name="Email" dataType="Custom" regexp="^/w+([-+.]/w+)*@/w+([-.]//w+)*/./w+([-.]/w+)*$" msg="信箱格式不正确">
 
Validator的必要属性是dataType和msg(区分大小写),然后根据dataType值的不同,会引发出不同的属性。因为程序中已经集成Email地址格式的正则,所以可以直接用dateType="Email"进行验证,如果对Email地址的格式有不同的限制,可以用自定义的正则来验证(参考第二段代码)。

--------------------------------------------------------------------------------------------

验证下拉菜单是否选中

代码示例:
<select name="Operation" dataType="Require" msg="未选择所用操作系统" >
<option value="">选择您所用的操作系统</option>
<option value="Win98">Win98</option>
<option value="Win2k">Win2k</option>
<option value="WinXP">WinXP</option>
</select>
注意,对于IE,在option中没写value属性时IE的解释引擎将自动设置其值为空,而Firefox时将自动设置其值为text属性址。例如,在示例代码中如果第一个option不写value属性,IE中将得到value为空,而Firefox为"选择您所用的操作系统"。

--------------------------------------------------------------------------------------------

验证是否选中单选按钮组中的一个

代码示例:
广东<input name="Province" value="1" type="radio">
陕西<input name="Province" value="2" type="radio">
浙江<input name="Province" value="3" type="radio">
江西<input name="Province" value="4" type="radio" dataType="Group" msg="必须选定一个省份" >
对于单/多选按钮组的验证,dataType属性都为Group,然后只需在按钮组的最后一个写上dataType和msg属性。
注意,要成为单/多选按钮组,它们必须具有相同的name属性值。

--------------------------------------------------------------------------------------------

限制多选按钮组的选中个数

代码示例:
运动<input name="Favorite" value="1" type="checkbox">
上网<input name="Favorite" value="2" type="checkbox">
听音乐<input name="Favorite" value="3" type="checkbox">
看书<input name="Favorite" value="4" type="checkbox"" dataType="Group" min="2" max="3" msg="必须选择2~3种爱好">
要限制多选按钮组的选中个数,必须设置min和max属性。min属性用于设定选中个数的下限,max为上限,默认时min为1,max为多选按钮组的个数。

--------------------------------------------------------------------------------------------

完整示例:运行 demo.html

--------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------- 
***************************************************************************************************************************************************************************************/

 

 

 

 

 

 

 

 

如发现有问题请与本人联系:
  MSN:hiyu2218@hotmail.com
  QQ:147204701
  Email:
hiyu2218@yahoo.com.cn

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值