简体   繁体   中英

how to validate multiple textbox for date using javascript

The below code is used to validate start and end date(two textbox and date is selected from calendar)when a button is clicked.The code works fine.The problem is i have 8 more start and end date to validate.so can anyone tell me a common code to validate all the start and end date because of the code length.

function validated() {
   var cal1=document.getElementById('<%=EndDateTwo.ClientId%>').value;
   var cal2= document.getElementById('<%=StartDateTwo.ClientId%>').value;
         if (cal1 == '' || cal2 == '') {
                alert("Start Date and End Date  can not bleft blank.");
                return false;
            }
            var dt1 = Date.parse(cal1);
            var dt2 = Date.parse(cal2);
            if (dt1 <= dt2) {
                alert("End Date must occur after the Start date ");
                return false;
            }
            return true;

I am using html button to call this

<asp:Button ID="Button2"  OnClientClick="return validated();" runat="server" Text="Enable" />

您可以创建一个validate(cal1, cal2)方法validate(cal1, cal2)对您要在validate()方法中进行validate()每个日期对调用此方法

如果将元素ID传递给函数,则可以在每对日期中重用它。

function validated(){


 var EndDate1=document.getElementById('<%=EndDate1.ClientId%>').value;
 var StartDate1=document.getElementById('<%=StartDate1.ClientId%>').value;
  var EndDate2=document.getElementById('<%=EndDate2.ClientId%>').value;
 var StartDate2=document.getElementById('<%=StartDate2.ClientId%>').value;
//So on

   validatedCommon(EndDate1,StartDate1);
   validatedCommon(EndDate2,StartDate2);

//So on
}

function validatedCommon(cal1,cal2) {

         if (cal1 == '' || cal2 == '') {
                alert("Start Date and End Date  can not bleft blank.");
                return false;
            }
            var dt1 = Date.parse(cal1);
            var dt2 = Date.parse(cal2);
            if (dt1 <= dt2) {
                alert("End Date must occur after the Start date ");
                return false;
            }
            return true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM