日期格式驗證javascript

來源:互聯網
上載者:User

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<HTML>

<HEAD>

<%@ page

language="java"

contentType="text/html; charset=GBK"

pageEncoding="GBK"

%>

<META http-equiv="Content-Type" content="text/html; charset=GBK">

<META name="GENERATOR" content="IBM WebSphere Studio">

<META http-equiv="Content-Style-Type" content="text/css">

<LINK href="theme/Master.css" rel="stylesheet" type="text/css">

<TITLE>test.jsp</TITLE>

</HEAD>

<BODY>

<form action="" method="post" onsubmit="return validateDate(this)">

<input type="text" name="sailTime" />

<input type="submit" />

</form>

<script language="javaScript">

function validateDate(form)

{

var i=0;

var theMsg="";

 var time=trim(form.sailTime.value);

  if(time=="") return;

  var reg="HHmm";

  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){//驗證格式是否合法

    theMsg+= ++i + "日期格式不正確\n";

    alert(theMsg);

    return false;

  }

  return true;

}

</script>

</BODY>

</HTML>

用Regex和javascript對錶單進行全面驗證
作者:  來源:網頁教學網  更新日期:2005-02-26  瀏覽次數:
213

代碼:<!--

使用時請將下面的javascript代碼存到一個單一的js檔案中。

1、表單要求

 <form name="formname" onSubmit="return validateForm(this)"></form>

 將對錶單中的所有以下類型的域依次驗證,所有驗證是去除了前置和尾碼空格的,要注意是區分大小寫。

2、空值驗證

 表單中任意域加上emptyInfo屬性將對此域是否為空白進行驗證(可以和最大長度驗證\一般驗證方式同時使用)。

 無此屬性視為此域允許空值。

  如:<input type="text" name="fieldNamename" emptyInfo="欄位不可為空!">

3、最大長度驗證(可以和空值驗證、一般驗證方式同時使用):

 <input type="text" name="fieldNamename" maxlength="20" lengthInfo="最大長度不能超過20!">

 或,<textarea maxlength="2000" lengthInfo="最大長度不能超過2000!">

3、一般驗證方式(不對空值做驗證):

  如:<input type="text" validator="^(19|20)[0-9]{2}$" errorInfo="不正確的年份!" >

4、標準驗證(不與其它驗證方式同時使用):

 全部通過<input type="hidden">來實現,並且不需要name屬性以免提交到伺服器。

  4.1、合法日期驗證:

  <input type="text" name="yearfieldName" value="2004">註:這裡也可以是<select name="yearfieldName"></select>,以下同

  <input type="text" name="monthfieldName" value="02">

  <input type="text" name="dayfieldName" value="03">

  <input type="hidden" validatorType="DateGroup" year="yearfieldName" month="monthfieldName" day="dayfieldName" errorInfo="不正確的日期!">

  yearfieldName、monthfieldName、dayfieldName分別為年月日欄位,月和日可以是兩位(MM)或一位格式(M),

  此處不對每個欄位分別檢驗(如果要檢驗,請在年月日三個域分別使用前面的一般驗證方式),只對日期的最大值是否合法檢查;

 4.2、日期格式驗證(請注意,此驗證不對日期是否有效進行驗證,還未找到從格式中得到年月日資料的方法^_^):

  <input type="text" name="datefieldName" value="2003-01-03 21:31:00">

  <input type="hidden" validatorType="Date" fieldName="datefieldName"; format="yyyy-MM-dd HH:mm:ss" errorInfo="不正確的日期!">

  其中格式僅對y、M、d、H、m、s進行支援(其它字元視為非時間的字元)

 4.3、列表驗證:

  檢驗列表(checkbox、redio、select)是否至少選中了一條記錄(對select主要用於多項選擇)

  <input type="checkbox" name="checkbox1">

  <input type="hidden" validatorType="Checkbox" fieldName="checkbox1" errorInfo="請至少選中一條記錄!">

  其中validatorType可以是Checkbox、R、Select;

  對於一個select表單,如果要求選擇一條不能是第一條的記錄,請用下列方式:

  <select name="select1" emptyInfo="請選擇一個選項!">

  <option value="">==請選擇==</option>

  <option value="1">1</option>

  <select>

 4.4、Email驗證:

  <input type="text" name="email">

  <input type="hidden" fieldName="email" validatorType="Email" separator="," errorInfo="不正確的Email!">

  其中separator為可選項,表示輸入多個email時的分隔字元(無此選項只能是一個地址)

 4.5、加入其它javascript操作:

 <script type="text/javascript">

  function functionname(){

    自訂方法

  }

 </script>

 表單中加入<input type="hidden" validatorType="javascript" functionName="functionname">(此時emptyInfo等屬性無效)

  時將調用function屬性中指定的javascript方法(要求方法返回true或false,返回false將不再驗證表單,也不提交表單)。

5、在表單通過驗證提交前disable一個按鈕(也可將其它域disable,不能與其它驗證同在一個域),不要求按鈕是表單中的最後一個

 <input type="button" name="提交" validatorType="disable">

6、不驗證表單

  <input type="hidden" name="validate" value="0" functionName="functionname">

 當validator域值為0時不對錶單進行驗證,直接提交表單或執行指定function並返回true後提交表單

 functionName為可選

-->

<script type="text/javascript">

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);

    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);

}

function validateDate(date,format,alt){

  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;

}

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.value);

  var m=parseInt(month.value);

  var d=parseInt(day.value);

  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;

}

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;

}

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;

}

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;

}

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){// 若驗證通過則返回true

  var disableList=new Array();

  var field = theForm.elements; // 將表單中的所有元素放入數組

  for(var i = 0; i < field.length; i++){

    var vali=theForm.validate;

 if(vali!=null){

   if(vali.value=="0"){

     var fun=vali.functionName;

  if(fun!=null){

    return eval(fun+"()");

  }

  else{

    return true;

  }

   }

 }

    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;

    }

    var lengthInfo=field[i].lengthInfo;//最大長度驗證

    if(lengthInfo!=null&&getStringLength(value)>field[i].maxLength){

      alert(lengthInfo);

      field[i].focus();

      return false;

    }

    var validatorType=field[i].validatorType;

    if(validatorType!=null){//其它javascript

      var rs=true;

      if(validatorType=="javascript"){

        eval("rs="+field[i].functionName+"()");

        if(rs==false){

          return false;

        }

        else{

          continue;

        }

      }

      else if(validatorType=="disable"){//提交表單前disable的按鈕

        disableList.length++;

        disableList[disableList.length-1]=field[i];

        continue;

      }

      else if(validatorType=="Date"){

        rs=validateDate(theForm.elements(field[i].fieldName),field[i].format,field[i].errorInfo);

      }

      else if(validatorType=="DateGroup"){

        rs=validateDateGroup(theForm.elements(field[i].year),theForm.elements(field[i].month),theForm.elements(field[i].day),field[i].errorInfo);

      }

      else if(validatorType=="Checkbox"){

        rs=validateCheckbox(theForm.elements(field[i].fieldName),field[i].errorInfo);

      }

      else if(validatorType=="Radio"){

        rs=validateRadio(theForm.elements(field[i].fieldName),field[i].errorInfo);

      }

      else if(validatorType=="Select"){

        rs=validateSelect(theForm.elements(field[i].fieldName),field[i].errorInfo);

      }

      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; // 擷取其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;

}

</script>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.