<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>vForm表單驗證程序</title>
<style type="text/css">
<!--
div.info {
 width: 170px;
 overflow:visible;
 height:auto;
 font-size: small;
 position: absolute;
 background-color: #FFffdd;
 border: 1px solid #000;
 filter:progid:DXImageTransform.Microsoft.Shadow(color=#111111,direction=135,strength=3);
 top: 375px;
 padding: 5px;
 left: 671px;
}
div.info_title

.err{
 padding: 5px;
 height: 50px;
 width: 24em;
 position: absolute;
 background-color: #FFFFCC;
 left: 196px;
 top: 114px;
 font-size: small;
 opacity:0.5;
 border: 1px double #333333;
 filter: Shadow(Color=#000000, Direction=135);
 filter:progid:DXImageTransform.Microsoft.Shadow(color=#111111,direction=135,strength=5);

}
#form1 .text_input {
 border-top: 1px solid #333333;
 border-right: 1px solid #999999;
 border-bottom: 1px solid #ddd;
 border-left: 1px solid #000000;
}
.info_title {
 color: #FF0000;
 background: #ACB9D1;
}
#form1 {
 position: static;
 left: 581px;
 top: 463px;
 border: 1px solid #3300FF;
 padding: 5px;
 ;
}
#imok {
 display: block;
 position: absolute;
 height:315px;
 overflow:scroll;
 left: 100px;
 top: 100px;
 width: 306px;
}
.title h1 {
 background: #33CCFF;
 border-bottom: medium solid #3366FF;
}
.title p {
 font-size: medium;
 text-indent: 2em;
}
body {
 font-family: Verdana, Arial, Helvetica, sans-serif;
 font-size: medium;
}

code {
 font: 12px/18px "lucida Grande", verdana, lucida, Arial, helvetica, "宋體", sans-serif;
 border:1px solid #0099cc;
 padding:5px;
 margin: 5px;
 width: 80%;
 color: #000;
 background-color: #ddedfb;
 display: block;
}

-->
</style>
<script language="JavaScript" type="text/javascript">
//程序基本思路:通過擴展對象來實現,將String擴展 將默認的表單元素擴展 定義兩個自定義對象。
//String.isEmail
//String.isUrl
//表單元素.required
//表單元素.isvalid
//表單元素.validate
//

//字符串驗證擴展
//├電子郵件驗證
String.prototype.isEmail = function(){
 var tmpStr = this;
 var email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
 return email.test(tmpStr)
}
//├http地址驗證
String.prototype.isUrl = function(){
 var url = /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/;
 var tmpStr = this;
 return url.test(tmpStr);
}
//├日期驗證(第一部分)
String.prototype.isDateTime = function(){
 if(Date.parse(this)||Date.parseDate(this))
 {
  return true;
 }
 else
 {
  return false;
 }
}
String.prototype.isInteger = function()
{
 var _i = /^[-\+]?\d+$/;
 var _s = this;
 return _i.test(_s);
}
Date.prototype.toIsoDate = function()
{
 var _d = this;
 var _s;
 _Y =_d.getFullYear();
 _M = _d.getMonth() + 1;
 _D = _d.getDate();
 _H = _d.getHours();
 _I = _d.getMinutes();
 _S = _d.getSeconds();
 with(_d)
 {
  _s = [getMonth() + 1,getDate(),getHours(),getMinutes(),getSeconds()];
 }
 for(var i = 0; i < _s.length; i++)
 {
  if (_s[i].toString().length == 1)_s[i]= '0'+_s[i];
 }
  return (_Y + '-'+_s[0]+'-'+_s[1]+' '+_s[2]+':'+_s[3]+':'+_s[4])
}
//├日期驗證(第二部分)
Date.parseDate = function(str, fmt) {
 fmt = fmt||"%Y-%m-%d %H:%M";
 var today = new Date();
 var y = 0;
 var m = -1;
 var d = 0;
 var a = str.split(/\W+/);
 var b = fmt.match(/%./g);
 var i = 0, j = 0;
 var hr = 0;
 var min = 0;
 for (i = 0; i < a.length; ++i) {
  if (!a[i])
   continue;
  switch (b[i]) {
      case "%d":
      case "%e":
   d = parseInt(a[i], 10);
   break;

      case "%m":
   m = parseInt(a[i], 10) - 1;
   break;

      case "%Y":
      case "%y":
   y = parseInt(a[i], 10);
   (y < 100) && (y += (y > 29) ? 1900 : 2000);
   break;

      case "%b":
      case "%B":
   for (j = 0; j < 12; ++j) {
    if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
   }
   break;

      case "%H":
      case "%I":
      case "%k":
      case "%l":
   hr = parseInt(a[i], 10);
   break;

      case "%P":
      case "%p":
   if (/pm/i.test(a[i]) && hr < 12)
    hr += 12;
   else if (/am/i.test(a[i]) && hr >= 12)
    hr -= 12;
   break;

      case "%M":
   min = parseInt(a[i], 10);
   break;
  }
 }
 if (isNaN(y)) y = today.getFullYear();
 if (isNaN(m)) m = today.getMonth();
 if (isNaN(d)) d = today.getDate();
 if (isNaN(hr)) hr = today.getHours();
 if (isNaN(min)) min = today.getMinutes();
 if (y != 0 && m != -1 && d != 0)
  return new Date(y, m, d, hr, min, 0);
 y = 0; m = -1; d = 0;
 for (i = 0; i < a.length; ++i) {
  if (a[i].search(/[a-zA-Z]+/) != -1) {
   var t = -1;
   for (j = 0; j < 12; ++j) {
    if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; }
   }
   if (t != -1) {
    if (m != -1) {
     d = m+1;
    }
    m = t;
   }
  } else if (parseInt(a[i], 10) <= 12 && m == -1) {
   m = a[i]-1;
  } else if (parseInt(a[i], 10) > 31 && y == 0) {
   y = parseInt(a[i], 10);
   (y < 100) && (y += (y > 29) ? 1900 : 2000);
  } else if (d == 0) {
   d = a[i];
  }
 }
 if (y == 0)
  y = today.getFullYear();
 if (m != -1 && d != 0)
  return new Date(y, m, d, hr, min, 0);
 return today;
};
//擴展完成

//對象定義

var vform = new Object;
//獲取彈出提示的顯示位置
vform.getAbsolutePos = function(el) {
 var _p = { x: 0, y: 0 };
  do{
    _p.x += (el.offsetLeft - el.scrollLeft);
    _p.y += (el.offsetTop - el.scrollTop);
  }
   while(el=el.offsetParent)
     return _p;
      };
vform.toString = function()
{
 return("vForm表單驗證程序\n版本:1.0beta\n作者:雷曉寶\n時間:2006-07-31\n網址:https://lxbzj.com\n許可:LGPL");
}
vform.rules = new Array;
vform.rules.add = function(obj,minLength,dataType,errmsg,maxLength,rule,patams)
{
    var curlen = this.length;
        this[curlen] = [obj,minLength,dataType,errmsg,maxLength,rule,patams];
        //this[curlen] = [ 0 ,    1    ,    2   ,   3  ,   4  ,  5 ,   6  ];

    return this.length;
}
vform.init= function()
{
 if(document.getElementById(this.form_id))
 {
  //獲取表單
  var o = document.getElementById(this.form_id);
  //遍歷規則
  for(var i = 0 ;i< this.rules.length;i++)
  {
   _r = this.rules[i]
   //如果存在元素,則添加驗證程序
   if(_o = o.elements[_r[0]])
   {
    //判斷是是否必填,是否有最小長度
    if(_r[1] > 0 )
    {
     _o.required = true;//必填的含義和最小長度為1是一樣的
     _o.minLength = parseInt(_r[1]);
    }
    else
    {
     _o.required = false;
     _o.minLength = 0;
    }
    //判斷是否有最大長度;
    if(_r[4])
    {
     _o.maxLength = parseInt(_r[4]);
    }
    //添加長度驗證函數
    _o.validLength = function ()
    {
     var b =true;
     if(this.minLength)
     {
      b = (this.minLength <= this.value.length);
     }
     if(this.type == 'textarea' && this.maxLength )
     {
      b = b && (this.maxLength >= this.value.length );
     }
     return (b);
    }
    //添加驗證,進行格式驗證
    switch(_r[2])
    {
     case 'e-mail':
      _o.validate = function()
      {
       this.isvalid = this.validLength() && this.value.isEmail();
       return (this.isvalid);
      };
      break;
     case 'url':
      _o.validate = function()
      {
       if (this.value.substring(0,7) != 'https://')this.value = 'https://' +this.value;
       this.isvalid = this.validLength() && this.value.isUrl();
       return (this.isvalid);
      }
      break;
     case 'date':
      _o.validate = function()
      {
       var _d = Date.parse(this.value)||Date.parseDate(this.value);
       this.value =  _d.toIsoDate();
       
       this.isvalid = this.validLength() && this.value.isDateTime();
       return (this.isvalid);
       a=a>b?1:1;
      }
      break;
     case 'number':
      _o.validate = function()
      {
       this.isvalid = this.validLength() && this.value.isInteger();
       return (this.isvalid);

      }
      break;
     case 'any':
      _o.validate = function()
      {
       this.isvalid = this.validLength();
       return  this.isvalid
      }
      break;
     default :
      var regexp = /^\\\w+$/;
      if ( regexp.test(_r[2]))//表示必須和同表單下的某個字段的值一樣。用于重復輸入的驗證
      {
       _el = _r[2].substring(1);
       if (o.elements[_el]){
        _o.equal = _el;
        _o.validate = function()
        {
         if(_o = this.form.elements[this.equal])
         {
          if ( (_o.value == this.value) && this.validLength())
          {
           return true;
          }else {
          return false;
          }
         }else{
          alert('setup error');
         }
        
        }
       }else
       {
        alert(_el + 'is not a valid form element');
        _o.validate = function(){return true;}
       }
      }
      var regexp1 = /^\\(==|!=|>=|<=|>|<)/;
      if ( regexp1.test(_r[2]) )
      {
       _s0 = _r[2];
       _s1 = RegExp.$1;
       _s2 = _s0.replace(regexp1,'');
       _operator = _s1.substring(0);//比較操作符
       var regexp2 = /^\w+$/;
       if (regexp2.test(_s2))//是一個標志符,整數 或者變量
       {
        _o.operation = _operator+_s2;
        _o.validate = function()
        {
         _b = true;
         if (this.value.length !=0)
         {
          _b = eval(this.value+this.operation+';');
         }         
         _b = _b && this.validLength();
         return _b;
        }
       }
      };
      break;
      
    }
    //添加驗證提示(div標簽)并初始化
    var _p = vform.getAbsolutePos(_o);
    _o.tip = new tip(_r[3],vform.err_class,_p.x+_o.offsetWidth+3,_p.y);

    _o.tip.init();
    //失去焦點時,開始驗證
    _o.onblur =function(e)
    {
     if(this.minLength || this.value.length >0)
     {
      if( this.validate() )
      {
       this.tip.hide();
      }else
      {
       this.tip.show();//顯示錯誤信息
       //this.focus(); 添加這句在ie里會導致死循環 :(
       return false;
      }
     }
    }
   }
  }
 //焦點驗證可能會失敗,所以最后需要表單提交前的驗證作為最后的補充。
  document.getElementById(this.form_id).onsubmit = function()
  {
   var valid = true;
   for(i=0;i<this.elements.length;i++)
   {
    _o = this.elements[i];
    if(_o.minLength && !_o.isvalid)
    {
     _o.tip.show();
     valid = false;
    }
   }
   return valid;
  }
 }
}
//彈出提示定義
function tip(text,className,x,y)
{
 var o = document.createElement("div");
 o.style.display = "none";
 o.innerHTML = text;
 //var t = document.createTextNode(text);
 document.body.appendChild(o);
 //o.appendChild(t);
 
 this.init = function(dis)
 {
  o.className = "info";
  o.style.left = x+"px";
  o.style.top = y+"px";
  o.style.zindex = 100;
  if(dis)
  {
   o.style.display = "";
  }
  else
  {
   o.style.display = "none";
  }
 }
 this.show = function()
 {
  o.style.display = "";
 }
 this.hide = function()
 {
  o.style.display = "none";
 }
}


function start()
{
  vform.form_id = 'form1';//必須是表單的id
  vform.err_class = 'info';//出錯提示的樣式
 //驗證規則,逐條填寫
vform.rules.add('frm_name',1,'e-mail','請您按照 user@domain.com 的格式輸入電子郵件地址。<br /><span style="color:#f00">必填項目</span>');
  vform.rules.add('myweb',1,'url','請您按照 https://www.domain.com 的格式輸入您的網址。<br /><span style="color:#f00">必填項目</span>');
  vform.rules.add('dateinput',0,'date','請按2000-03-05 的格式輸入日期。<br /><span style="color:#f00">必填項目</span>');
  vform.rules.add('qq',0,'number','這必須是一個整數');
  vform.rules.add('least10',10,'any','您必須至少填寫10個<br /><span style="color:#f00">必填項目</span>');
  vform.rules.add('ok100',1,'any','這里被限制為100個字符<br /><span style="color:#f00">必填項目</span>',100);
  vform.rules.add('r_pass0',5,'any','密碼最短5位最長20位<br /><span style="color:#f00">必填項目</span>',20);
  vform.rules.add('r_pass1',5,"\\r_pass0",'確認密碼錯誤<br /><span style="color:#f00">必填項目</span>',20);
  vform.rules.add('frm_sel',1,"\\>2",'必須大于2000<br /><span style="color:#f00">必填項目</span>');
  vform.init();
 
}

</script>
</head>
<body onload="start()">

<form id="form1" name="form1" method="get" action="">
 <label for="frm_name">e-mail:
 <input name="frm_name" type="text" class="text_input" id="frm_name" title="輸入一個電子郵箱地址"/>
 </label>
 *
 <p>
  <label for="r_pass0">輸入密碼:
  <input name="r_pass0" type="text" class="text_input" id="r_pass0" title="輸入您希望的密碼 " />
  </label>
 *</p>
 <p>
  <label for="r_pass1">密碼確認:
  <input name="r_pass1" type="text" class="text_input" id="r_pass1" title="將密碼確認一次" />
  </label>
 *</p>
 <p>
  <label for="frm_sel">選擇:
  <select name="frm_sel" id="frm_sel" title="請選擇一個答案">
   <option value="0">請選擇一個答案</option>
   <option value="1" selected="selected">1000</option>
   <option value="2">2000</option>
   <option value="3">3000</option>
   <option value="4">4000</option>
   <option value="5">5000</option>
   <option value="6">6000</option>
  </select>
</label>
 *</p>
 <p>
  <label for="input3">輸入網址:
  <input name="myweb" type="text" class="text_input" id="input3" title="輸入一個網址" onmousemove="" value="https://" maxlength="100"/>
  </label>
 *</p>
 <p>
  <label for="dateinput">輸入日期
  <input name="dateinput" type="text" class="text_input" title="輸入一個日期" id="dateinput"/>
</label>
 *</p>
 <p>
  <label for="mub">輸入數字
  <input name="qq" type="text" class="text_input" title="填寫數字" id="mub"/>
  </label>
 </p>
 <p>
  <label for="len">輸入任意但長度限制為10個
  <input name="least10" type="text" class="text_input" maxlength="88" id="len"/>
  *
  </label>
 </p>
 <p>
  <label for="text">只能輸入100個
  <textarea name="ok100" cols="40" rows="5" id="text" title="詳細內容"></textarea>
  *
  </label>
 </p>
 <p>
  <input type="submit" name="Submit" value="提交" />
  <button onclick="alert(vform)" >關于驗證程序</button>
 </p>
</form>
<!--具體的日期設置,必須放在body的結束標簽前面-->
<script type="text/javascript">
  vform .init();
    Calendar.setup({
   inputField     :    "dateinput",   // 把這個改成你需要的 id
   ifFormat       :    "%Y-%m-%d %H:%M", // format of the input field
   showsTime      :    true,
   //button     :    "dateinput_btn",
   timeFormat     :    "24"
   });
 </script>
<!--END具體的日期設置,必須放在body的結束標簽前面-->
<div class="title">
 <h1>vForm1.0beta</h1>
 <ul>
  <li>作者:雷曉寶</li>
  <li>時間:2006-08-08</li>
  <li>網址:https://lxbzj.com</li>
  <li>e-mail:lxbzmy@163.com</li>
  <li>許可:LGPL</li>
 </ul>
 <h2>功能簡述:</h2>
 <ol>
   <li>
     <h3>驗證:</h3>
     <ul>
       <li>http地址。</li>
          <li>時間日期</li>
       <li>e-mail</li>
       <li>數字</li>
       <li>字符長度檢查</li>
       <li>一項輸入與另一項輸入比較(例如:密碼的確認輸入)</li>
       <li>大小比較(只能有一個比較符號)</li>
        </ul>
   </li>
      <li>
        <h3>特點</h3>
        <ul>
          <li>擴展容易,可以方便的添加自己需要的驗證方式</li>
          <li>兼容性好(ie5,6 firefox,oprea)。</li>
        <li>可用性好,沒有使用alert()來彈出提示;</li>
        </ul>
      </li>
  </ol>
 <p> </p>
 <h2>使用方法</h2>
 <p>使用時,需要定義一個出錯提示框的樣式,本例的樣式為:<code>div.info {
     width: 170px;<br />
    overflow:visible;<br />
    height:auto;<br />
    font-size: small;<br />
    position: absolute;<br />
    background-color: #FFffdd;<br />
    border: 1px solid #000;<br />
    filter:progid:DXImageTransform.Microsoft.Shadow(color=#111111,direction=135,strength=3);<br />
    padding: 5px;<br />
    }</code></p>
 <p>然后在網頁&lt;head&gt;部分中添加<code>&lt;script type="text/javascript" src="calendar/calendar.js"&gt;&lt;/script&gt;</code><br />
   ,然后可以寫一個函數設置表單名稱,驗證規則,<code>function start()<br />
   {
   <br />
   vFormvform.form_id = 'form1';<br />
  vform.err_class = 'info';<br />
  // (obj,required(true/false),dataType,errmsg,minlen,maxlen,rule,patams)<br />
  //驗證規則,逐條填寫<br />
  vform.rules.add('frm_name',1,'e-mail','請您按照 user@domain.com 的格式輸入電子郵件地址。&lt;br /&gt;&lt;span style="color:#f00"&gt;必填項目&lt;/span&gt;');<br />
  vform.rules.add('myweb',1,'url','請您按照 https://www.domain.com 的格式輸入您的網址。&lt;br /&gt;&lt;span style="color:#f00"&gt;必填項目&lt;/span&gt;');<br />
  vform.rules.add('dateinput',0,'date','請按2000-03-05 的格式輸入日期。&lt;br /&gt;&lt;span style="color:#f00"&gt;必填項目&lt;/span&gt;');<br />
  vform.rules.add('qq',0,'number','這必須是一個整數');<br />
  vform.rules.add('least10',10,'any','您必須至少填寫10個&lt;br /&gt;&lt;span style="color:#f00"&gt;必填項目&lt;/span&gt;');<br />
  vform.rules.add('ok100',1,'any','這里被限制為100個字符&lt;br /&gt;&lt;span style="color:#f00"&gt;必填項目&lt;/span&gt;',100);<br />
   vform.init();<br />
   }</code>最后為body添加onload事件。   <code>   &lt;body onload="start();"&gt;
 </code></p>
 <p> </p>
</div>
</body>
</html>

創作者介紹
創作者 bgm 的頭像
bgm

bgm

bgm 發表在 痞客邦 留言(0) 人氣( 193 )