一些經常用到的js驗證代碼

function GridOver(mobj){
 originalcolor=mobj.style.backgroundColor;
 mobj.style.backgroundColor="#eaf2ff";
 originalfontcolor=mobj.style.color;
 mobj.style.color="Red";
}
function GridOut(mobj)       {
 mobj.style.backgroundColor=originalcolor;
 mobj.style.color=originalfontcolor;
}

function hello(){
 alert("123");
}
//計算字串長度,中文字算兩個字
function getStringLength(str){
  var endvalue=0;
  var sourcestr=new String(str);
  var tempstr;
  for (var strposition = 0; strposition < sourcestr.length; strposition ++) {
    tempstr=sourcestr.charAt(strposition);
    //有時會溢位,所以必須判斷小於 0
   //charCodeAt:返回一個整數,代表指定位置上字符的 Unicode 編碼。
    if (tempstr.charCodeAt(0)>255 || tempstr.charCodeAt(0)<0) {
      endvalue=endvalue+2;
    } else {
      endvalue=endvalue+1;
    }
  }
  return(endvalue);
}
function trim(str){
  if(str==null) return "";
  if(str.length==0) return "";
  var i=0,j=str.length-1,c;
  for(;i<str.length;i++){
    c=str.charAt(i);
    if(c!=' ') break;
  }
  for(;j>-1;j--){
    c=str.charAt(j);
    if(c!=' ') break;
  }
  if(i>j) return "";
  return str.substring(i,j+1);
}
//以指定的格式來驗證傳入的日期,傳入的 format 會轉換成 RegExp ,檢核錯誤時會秀傳入的 alt 訊息
function validateDate(date,format,alt){
    "yyyy/MM/dd"
  var time=trim(date.value);
  if(time=="") return;
  var reg=format;

  var reg=reg.replace(/yyyy/,"[0-9]{4}");
  var reg=reg.replace(/yy/,"[0-9]{2}");
  var reg=reg.replace(/MM/,"((0[1-9])|1[0-2])");
  var reg=reg.replace(/M/,"(([1-9])|1[0-2])");
  var reg=reg.replace(/dd/,"((0[1-9])|([1-2][0-9])|30|31)");
  var reg=reg.replace(/d/,"([1-9]|[1-2][0-9]|30|31))");
  var reg=reg.replace(/HH/,"(([0-1][0-9])|20|21|22|23)");
  var reg=reg.replace(/H/,"([0-9]|1[0-9]|20|21|22|23)");
  var reg=reg.replace(/mm/,"([0-5][0-9])");
  var reg=reg.replace(/m/,"([0-9]|([1-5][0-9]))");
  var reg=reg.replace(/ss/,"([0-5][0-9])");
  var reg=reg.replace(/s/,"([0-9]|([1-5][0-9]))");
  reg=new RegExp("^"+reg+"$");
  if(reg.test(time)==false){
    alert(alt);
    date.focus();
    return false;
  }
  return true;
}
//驗證傳入日期的正確性(呼叫前已經先經過 RegExp 檢核格式正確)
function validateDateGroup(year,month,day,alt){
  var array=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
  var y=parseInt(year,10);
  var m=parseInt(month,10);
  var d=parseInt(day,10);
  var maxday=array[m-1];
  if(m==2){
    if((y%4==0&&y%100!=0)||y%400==0){
      maxday=29;
    }
  }
  if(d>maxday){
    alert(alt);
    return false;
  }
  return true;
}
//檢查名稱相同的一羣 Checkbox  是否至少有一個被點選
function validateCheckbox(obj,alt){
  var rs=false;
  if(obj!=null){
    if(obj.length==null){
      return obj.checked;
    }
    for(i=0;i<obj.length;i++){
      if(obj[i].checked==true){
        return true;
      }
    }
  }
  alert(alt);
  return rs;
}
//檢查名稱相同的一羣 Radio  是否至少有一個被點選
function validateRadio(obj,alt){
  var rs=false;
  if(obj!=null){
    if(obj.length==null){
      return obj.checked;
    }
    for(i=0;i<obj.length;i++){
      if(obj[i].checked==true){
        return true;
      }
    }
  }
  alert(alt);
  return rs;
}
//檢查傳入的 Select 是否有被選擇
function validateSelect(obj,alt){
  var rs=false;
  if(obj!=null){
    for(i=0;i<obj.options.length;i++){
      if(obj.options[i].selected==true){
        return true;
      }
    }
  }
  alert(alt);
  return rs;
}
//檢查傳入的 Email 格式是否正確
function validateEmail(email,alt,separator){
  var mail=trim(email.value);
  if(mail=="") return;
  var em;
  var myReg = /^[_a-z0-9]+@([_a-z0-9]+/.)+[a-z0-9]{2,3}$/;
  if(separator==null){
    if(myReg.test(email.value)==false){
      alert(alt);
      email.focus();
      return false;
    }
  }
  else{
    em=email.value.split(separator);
    for(i=0;i<em.length;i++){
      em[i]=em[i].trim();
      if(em[i].length>0&&myReg.test(em[i])==false){
        alert(alt);
        email.focus();
        return false;
      }
    }
  }
  return true;
}
//驗證欄位的入口
function validateForm(theForm){
  var disableList=new Array();
  var field = theForm.elements;

  for(var i = 0; i < field.length; i++){
    //檢查 FORM 是否有自訂檢核 function ( function 名稱可自行指定 )
    //如果要使用 FORM  自訂檢核 function 設定如下
    //thisForm["validate"].value ="0" vlaue 如果不等於 "0" 則跳過此功能
    //thisForm["validate"].functionName ="Check"
    //function Check() {...}
    var vali=theForm.validate;
   if(vali!=null){
      if(vali.value=="0"){
        var fun=vali.functionName;
        if(fun!=null){
          return eval(fun+"()");
        }
        else{
           return true;
        }
      }
    }
    //當 form 的 element 有設定 emptyInfo 屬性時,檢核欄位值是否為空值
    var empty=false;
    var value=trim(field[i].value);
    if(value.length==0){
      empty=true;
    }
    var emptyInfo=field[i].emptyInfo;
    if(emptyInfo!=null&&empty==true){
      alert(emptyInfo);
      field[i].focus();
      return false;
    }
    //當 form 的 element 有設定 lengthInfo 屬性時,檢核欄位值長度是否超過
    var lengthInfo=field[i].lengthInfo;
    // getStringLength 認定中文字長度為 2
    if(lengthInfo!=null&&getStringLength(value)>field[i].maxLength){
      alert(lengthInfo);
      field[i].focus();
      return false;
    }
    //validatorType 是本系統支援的驗證型別,如果不是本系統支援的型別
    //則會採用  validator 中的 RegExp 的表達式,來驗證 Value 值
    var validatorType=field[i].validatorType;
    if(validatorType!=null){
      var rs=true;
      //如果要定義欄位自己的檢核 function ,則將  validatorType 設為 "javascript"
      //然後設定欄位的 functionName 屬性為欲執行 function 的名稱
      //例如 theForm.field.validatorType = "javascript"
      //       theForm.field.functionName = "fieldcheck"
      //       function fieldcheck() {...}
      if(validatorType=="javascript"){
        eval("rs="+field[i].functionName+"()");
        if(rs==false){
          return false;
        }
        else{
          continue;
        }
      }
      //如果完成所有欄位檢核之後,要將此欄位 disable  ,則將  validatorType 設為 "disable"
      //例如 theForm.field.validatorType = "disable"
      else if(validatorType=="disable"){
        disableList.length++;
        disableList[disableList.length-1]=field[i];
        continue;
      }
      //如果要以指定的格式來驗證欄位的日期格式,則將  validatorType 設為 "Date"
      //例如 theForm.field.validatorType = "Date"
      //       theForm.field.fieldName = "Birthday"
      //       theForm.field.format = "yyyy/MM/dd"
      //       theForm.field.errorInfo = "日期不正確..."
      else if(validatorType=="Date"){
        rs=validateDate(theForm.elements(field[i].fieldName),field[i].format,field[i].errorInfo);
      }

      //如果輸入民國年然後要驗證傳入日期的正確性,則將  validatorType 設為 "DateGroup"
      //先經過 RegExp 檢核格式正確後再呼叫 validateDateGroup 驗證傳入日期的正確性
      //例如 theForm.field.validatorType = "DateGroup";
      //       theForm.field.validator = /^([1-9]|[1-9][0-9]|1[0-9][0-9])//(0[1-9]|1[0-2])//(0[1-9]|[1-2][0-9]|30|31)$/;
      //       theForm.field.errorInfo = "日期不正確..." ;
      else if(validatorType=="DateGroup"){
        if(empty==false){
          var v = field[i].validator;
          if(!v) continue;
          var reg=new RegExp(v);

          if(reg.test(field[i].value)==false){
            alert(field[i].errorInfo);
            field[i].focus();
            rs = false;
            return false;
          }
          else{
            var strDateArray = field[i].value.split("/");
            if(strDateArray.length==3){
              var year = parseInt(strDateArray[0],10)+1911;
              var month = parseInt(strDateArray[1],10);
              var day = parseInt(strDateArray[2],10);
            }
            rs = validateDateGroup(year,month,day,field[i].errorInfo);
            if(rs==false)field[i].focus();
          }
        }
      }
      //如果要檢查名稱相同的一羣 Checkbox  是否至少有一個被點選,則將  validatorType 設為 "Checkbox"
      //例如 theForm.field.validatorType = "Checkbox";
      //       theForm.field.errorInfo = "請至少選擇一個..." ;
      //       theForm.field.fieldName = "chkType"
      else if(validatorType=="Checkbox"){
        rs=validateCheckbox(theForm.elements(field[i].fieldName),field[i].errorInfo);
      }
      //如果要檢查名稱相同的一羣 Radio  是否至少有一個被點選,則將  validatorType 設為 "Radio"
      //例如 theForm.field.validatorType = "Radio";
      //       theForm.field.errorInfo = "請至少選擇一個..." ;
      //       theForm.field.fieldName = "optSex"
      else if(validatorType=="Radio"){
        rs=validateRadio(theForm.elements(field[i].fieldName),field[i].errorInfo);
      }
      //如果要檢查 Select  是否有選取,則將  validatorType 設為 "Select"
      //例如 theForm.field.validatorType = "Select";
      //       theForm.field.errorInfo = "請選取..." ;
      //       theForm.field.fieldName = "cboType"
      else if(validatorType=="Select"){
        rs=validateSelect(theForm.elements(field[i].fieldName),field[i].errorInfo);
      }
      //如果要檢查 Email 欄位是否正確,則將  validatorType 設為 "Email"
      //例如 theForm.field.validatorType = "Email";
      //       theForm.field.errorInfo = "Email輸入不正確..." ;
      //       theForm.field.fieldName = "txtEmail"
      else if(validatorType=="Email"){
        rs=validateEmail(theForm.elements(field[i].fieldName),field[i].errorInfo);
      }
      else{
        alert("驗證類型不被支持, fieldName: "+field[i].name);
        return false;
      }
      //錯誤訊息皆已在檢核功能中顯示,此處直接返還
      if(rs==false){
        return false;
      }
    }
    else{
      if(empty==false){
        var v = field[i].validator;
        if(!v) continue;
        var reg=new RegExp(v);
        if(reg.test(field[i].value)==false){
          alert(field[i].errorInfo);
          field[i].focus();
          return false;
        }
      }
    }
  }
  for(i=0;i<disableList.length;i++){
    disableList[i].disabled=true;
  }
  return true;
}
//補強的浮點運算,含加減乘除
function demicalFloat(numberA,numberB,type)
{
  var h=(type=="*")? "+":"-";
  var c=[get(numberA),get(numberB)];
  var A=c[0][1];   //numberA 的數字
  var B=c[1][1];   //numberB 的數字
  var pointA=c[0][0];  //numberA 的小數位數
  var pointB=c[1][0];  //numberB 的小數位數

  if (type=="*" || type=="/")
  {
    var k1=eval("numberA"+type+"numberB");
    var k2=eval("(A"+type+"B)");
    if (get(k1)[1]==k2) return k1;
    else return (pointA+pointB==0? k1:eval(k2+"/Math.pow(10,pointA"+h+"pointB)"));
  }
  else if (type=="+" || type=="-")
  {
    var pointL=pointA;
    if (pointA<pointB) pointL=pointB;
    numberA=demicalFloat(numberA,Math.pow(10,pointL),"*");
    numberB=demicalFloat(numberB,Math.pow(10,pointL),"*");
    return eval("numberA"+type+"numberB")/Math.pow(10,pointL);
  }
  else return "[ Can't calculate! ]"
}

function get(number)
{
  number=""+number;
  if (number.indexOf(".")==-1) return [0,parseInt(number)];
  //小數位數
  var po=number.split(".")[1].length;
  //轉成整數 4.1 --> 41 , 4.33 --> 433
  var st=number.split(".").join("");
  //將前置 0 拿掉
  for (var i=0;i<st.length;i++) if (st.charAt(0)=="0") st=st.substr(1,st.length);
  //傳回一個陣列,陣列 0 存小數位數, 陣列 1 存數字
  return [po,parseInt(st)];

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章