JavaScript - Date Validation Question.
Hello, i have a question about date validation. I'm new to javascript and am still learning. I was wondering if anyone could help me out with a problem i am facing. I want my code to be able to validate the date in different formats other then 01/25/2007. I would like the code to be able to validate 1-25-07, 1-25-2007, or 01/25/2007. Here is the code i have thus far which works with the 01/25/2007 format. Any ideas on how i could make this code work to validate the other formats? Thank you for your time, here is the code.
<script language = "Javascript"> var dtCh= "/"; var minYear=1900; var maxYear=2100; function isInteger(s){ var i; for (i = 0; i < s.length; i++){ var c = s.charAt(i); if (((c < "0") || (c > "9"))) return false; } return true; } function stripCharsInBag(s, bag){ var i; var returnString = ""; for (i = 0; i < s.length; i++){ var c = s.charAt(i); if (bag.indexOf(c) == -1) returnString += c; } return returnString; } function daysInFebruary (year){ return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 ); } function DaysArray(n) { for (var i = 1; i <= n; i++) { this[i] = 31 if (i==4 || i==6 || i==9 || i==11) {this[i] = 30} if (i==2) {this[i] = 29} } return this } function isDate(dtStr){ var daysInMonth = DaysArray(12) var pos1=dtStr.indexOf(dtCh) var pos2=dtStr.indexOf(dtCh,pos1+1) var strMonth=dtStr.substring(0,pos1) var strDay=dtStr.substring(pos1+1,pos2) var strYear=dtStr.substring(pos2+1) strYr=strYear if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1) if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1) for (var i = 1; i <= 3; i++) { if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1) } month=parseInt(strMonth) day=parseInt(strDay) year=parseInt(strYr) if (pos1==-1 || pos2==-1){ alert("The date format should be : mm/dd/yyyy") return false } if (strMonth.length<1 || month<1 || month>12){ alert("Please enter a valid month") return false } if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){ alert("Please enter a valid day") return false } if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){ alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear) return false } if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){ alert("Please enter a valid date") return false } return true } function ValidateForm(){ var dt=document.frmSample.txtDate if (isDate(dt.value)==false){ dt.focus() return false } return true } </script> <form name="frmSample" method="post" action="" onSubmit="return ValidateForm()"> <p>Enter a Date <font color="#CC0000"><b>(mm/dd/yyyy)</b></font> : <input type="text" name="txtDate" maxlength="10" size="15"> </p> <p> <input type="submit" name="Submit" value="Submit"> </p> </form> Similar TutorialsHi, Got input boxes for begin and end dates - using JQuery for date picker calendar for each. Need to validate 2 things - 1 is that end date is => than begin date, 2 is that user enters date into begin date rather than just numbers. I got date picker JQuery from another office where I work and can not change their parameters or code. So my input boxes allow for date picker selection or manual data entry. The end date input box can be empty if user only inputting one day for begin date and not a range. Also have 3 more begin/end date input box sets which are not visible until user clicks "Add Row" button - one click, one set added. Want to insure if user added row and input date then removed row (clicked "Remove Row" button) that the data entered is removed and not inserted into database. Add & remove rows: Code: <script type="text/javascript"> var showing = 0; function showAnother() { if ( showing <= 3 ) { ++showing; document.getElementById("row"+showing).style.display =""; } if ( showing == 3) { alert("Maximum number of rows allowed."); } } </script> <script type="text/javascript"> function removeRow() { if ( showing >= 0 ) { document.getElementById("row"+showing).style.display ="none"; showing--; } if ( showing == 0 ) { return true; } } </script> Begin & end date input boxes: Code: <td><input style="width: 70px" type="text" id="startdate1" name="startdate1" /></td> <td><input name="stopdate1" style="width: 70px" type="text" id="stopdate1"/></td> Other 3 begin & end date input boxes same with names increased by one digit - startdate2/stopdate2, and so on to 4. Thanks, John hi there all, i am working on an application built using JSP, and many screens in the application have date fields that use a calendar.js file to show and pick the date. the requirement is to set a validation where the user cannot enter a date bigger than the current date, fair enough, but my problem is that i am a newb and this whole application is built by ppl that don't work for my company no more so im stuck with it, below is the calendar.js file maybe u guys could help me on where should i put the validation. thanks in advance Code: var weekend = [4,5]; var weekendColor = "#EAF4D6"; var fontface = "Verdana"; var fontsize = 1; var TYPE = 1; // 1 for arabic and 2 for hirji var gNow = new Date(); var ggWinCal; isNav = (navigator.appName.indexOf("Netscape") != -1) ? true : false; isIE = (navigator.appName.indexOf("Microsoft") != -1) ? true : false; Calendar.Months = ["�����", "������", "����", "�����", "����", "�����", "�����", "�����", "������", "�������", "�����", "������"]; // Non-Leap year Month days.. Calendar.DOMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; // Leap year Month days.. Calendar.lDOMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; function Calendar(p_item, p_WinCal, p_month, p_year, p_format) { if ((p_month == null) && (p_year == null)) return; if (p_WinCal == null) this.gWinCal = ggWinCal; else this.gWinCal = p_WinCal; if (p_month == null) { this.gMonthName = null; this.gMonth = null; this.gYearly = true; } else { this.gMonthName = Calendar.get_month(p_month); this.gMonth = new Number(p_month); this.gYearly = false; } this.gYear = p_year; this.gFormat = p_format; this.gBGColor = "white"; this.gFGColor = "black"; this.gTextColor = "black"; this.gHeaderColor = "black"; this.gReturnItem = p_item; } Calendar.get_month = Calendar_get_month; Calendar.get_daysofmonth = Calendar_get_daysofmonth; Calendar.calc_month_year = Calendar_calc_month_year; Calendar.print = Calendar_print; function Calendar_get_month(monthNo) { return Calendar.Months[monthNo]; } function Calendar_get_daysofmonth(monthNo, p_year) { /* Check for leap year .. 1.Years evenly divisible by four are normally leap years, except for... 2.Years also evenly divisible by 100 are not leap years, except for... 3.Years also evenly divisible by 400 are leap years. */ if ((p_year % 4) == 0) { if ((p_year % 100) == 0 && (p_year % 400) != 0) return Calendar.DOMonth[monthNo]; return Calendar.lDOMonth[monthNo]; } else return Calendar.DOMonth[monthNo]; } function Calendar_calc_month_year(p_Month, p_Year, incr) { /* Will return an 1-D array with 1st element being the calculated month and second being the calculated year after applying the month increment/decrement as specified by 'incr' parameter. 'incr' will normally have 1/-1 to navigate thru the months. */ var ret_arr = new Array(); if (incr == -1) { // B A C K W A R D if (p_Month == 0) { ret_arr[0] = 11; ret_arr[1] = parseInt(p_Year) - 1; } else { ret_arr[0] = parseInt(p_Month) - 1; ret_arr[1] = parseInt(p_Year); } } else if (incr == 1) { // F O R W A R D if (p_Month == 11) { ret_arr[0] = 0; ret_arr[1] = parseInt(p_Year) + 1; } else { ret_arr[0] = parseInt(p_Month) + 1; ret_arr[1] = parseInt(p_Year); } } return ret_arr; } function Calendar_print() { ggWinCal.print(); } function Calendar_calc_month_year(p_Month, p_Year, incr) { /* Will return an 1-D array with 1st element being the calculated month and second being the calculated year after applying the month increment/decrement as specified by 'incr' parameter. 'incr' will normally have 1/-1 to navigate thru the months. */ var ret_arr = new Array(); if (incr == -1) { // B A C K W A R D if (p_Month == 0) { ret_arr[0] = 11; ret_arr[1] = parseInt(p_Year) - 1; } else { ret_arr[0] = parseInt(p_Month) - 1; ret_arr[1] = parseInt(p_Year); } } else if (incr == 1) { // F O R W A R D if (p_Month == 11) { ret_arr[0] = 0; ret_arr[1] = parseInt(p_Year) + 1; } else { ret_arr[0] = parseInt(p_Month) + 1; ret_arr[1] = parseInt(p_Year); } } return ret_arr; } // This is for compatibility with Navigator 3, we have to create and discard one object before the prototype object exists. new Calendar(); Calendar.prototype.getMonthlyCalendarCode = function() { var vCode = ""; var vHeader_Code = ""; var vData_Code = ""; // Begin Table Drawing code here.. vCode = vCode + "<TABLE BORDER=1 WIDTH='100%' BGCOLOR=\"" + this.gBGColor + "\">"; vHeader_Code = this.cal_header(); vData_Code = this.cal_data(); vCode = vCode + vHeader_Code + vData_Code; vCode = vCode + "</TABLE>"; return vCode; } Calendar.prototype.show = function() { var vCode = ""; this.gWinCal.document.open(); // Setup the page... this.wwrite("<html>"); this.wwrite("<head><title>������� ��������</title>"); this.wwrite("</head>"); this.wwrite("<body dir=\"rtl\"" + "link=\"" + this.gLinkColor + "\" " + "vlink=\"" + this.gLinkColor + "\" " + "alink=\"" + this.gLinkColor + "\" " + "text=\"" + this.gTextColor + "\">"); this.wwriteA("<FONT FACE='" + fontface + "' SIZE=1 COLOR='#914848'><B>"); this.wwriteA(this.gMonthName + " " + this.gYear); this.wwriteA("</B><BR>"); // Show navigation buttons var prevMMYYYY = Calendar.calc_month_year(this.gMonth, this.gYear, -1); var prevMM = prevMMYYYY[0]; var prevYYYY = prevMMYYYY[1]; var nextMMYYYY = Calendar.calc_month_year(this.gMonth, this.gYear, 1); var nextMM = nextMMYYYY[0]; var nextYYYY = nextMMYYYY[1]; this.wwrite("<TABLE width='100%' BORDER=1 CELLSPACING=0 CELLPADDING=0 BGCOLOR='#EAF4D6'><TR><TD BGCOLOR='#EAF4D6' ALIGN=center><FONT FACE='Verdana' SIZE='1'>"); this.wwrite("[<A HREF=\"" + "javascript:window.opener.Build(" + "'" + this.gReturnItem + "', '" + this.gMonth + "', '" + (parseInt(this.gYear)-1) + "', '" + this.gFormat + "'" + ");" + "\"><<<\/A>]</B></FONT></TD><TD BGCOLOR='#EAF4D6' ALIGN=center><FONT FACE='Verdana' SIZE='1'>"); this.wwrite("[<A HREF=\"" + "javascript:window.opener.Build(" + "'" + this.gReturnItem + "', '" + prevMM + "', '" + prevYYYY + "', '" + this.gFormat + "'" + ");" + "\"><<\/A>]</FONT></TD><TD BGCOLOR='#EAF4D6' ALIGN=center><FONT FACE='Verdana' SIZE='1'>"); this.wwrite("[<A HREF=\"javascript:window.print();\">Print</A>]</FONT></TD><TD BGCOLOR='#EAF4D6' ALIGN=center><FONT FACE='Verdana' SIZE='1'>"); this.wwrite("[<A HREF=\"" + "javascript:window.opener.Build(" + "'" + this.gReturnItem + "', '" + nextMM + "', '" + nextYYYY + "', '" + this.gFormat + "'" + ");" + "\">><\/A>]</FONT></TD><TD BGCOLOR='#EAF4D6' ALIGN=center><FONT FACE='Verdana' SIZE='1'>"); this.wwrite("[<A HREF=\"" + "javascript:window.opener.Build(" + "'" + this.gReturnItem + "', '" + this.gMonth + "', '" + (parseInt(this.gYear)+1) + "', '" + this.gFormat + "'" + ");" + "\">>><\/A>]</FONT></TD></TR></TABLE><BR>"); // Get the complete calendar code for the month.. vCode = this.getMonthlyCalendarCode(); this.wwrite(vCode); this.wwrite("</font></body></html>"); this.gWinCal.document.close(); } Calendar.prototype.showY = function() { var vCode = ""; var i; var vr, vc, vx, vy; // Row, Column, X-coord, Y-coord var vxf = 285; // X-Factor var vyf = 200; // Y-Factor var vxm = 10; // X-margin var vym; // Y-margin if (isIE) vym = 75; else if (isNav) vym = 25; this.gWinCal.document.open(); this.wwrite("<html>"); this.wwrite("<head><title>������� ��������</title>"); this.wwrite("<style type='text/css'>\n<!--"); for (i=0; i<12; i++) { vc = i % 3; if (i>=0 && i<= 2) vr = 0; if (i>=3 && i<= 5) vr = 1; if (i>=6 && i<= 8) vr = 2; if (i>=9 && i<= 11) vr = 3; vx = parseInt(vxf * vc) + vxm; vy = parseInt(vyf * vr) + vym; this.wwrite(".lclass" + i + " {position:absolute;top:" + vy + ";left:" + vx + ";}"); } this.wwrite("-->\n</style>"); this.wwrite("</head>"); this.wwrite("<body " + "link=\"" + this.gLinkColor + "\" " + "vlink=\"" + this.gLinkColor + "\" " + "alink=\"" + this.gLinkColor + "\" " + "text=\"" + this.gTextColor + "\">"); this.wwrite("<FONT FACE='" + fontface + "' SIZE=2><B>"); this.wwrite("Year : " + this.gYear); this.wwrite("</B><BR>"); // Show navigation buttons var prevYYYY = parseInt(this.gYear) - 1; var nextYYYY = parseInt(this.gYear) + 1; //Here this.wwrite("<TABLE width='100%' BORDER=1 CELLSPACING=0 CELLPADDING=0 BGCOLOR='#B6DADA'><TR BGCOLOR='#B6DADA'><TD BGCOLOR='#B6DADA' ALIGN=center>"); this.wwrite("[<A HREF=\"" + "javascript:window.opener.Build(" + "'" + this.gReturnItem + "', null, '" + prevYYYY + "', '" + this.gFormat + "'" + ");" + "\" alt='Prev Year'><<<\/A>]</TD><TD ALIGN=center>"); this.wwrite("[<A HREF=\"javascript:window.print();\">Print</A>]</TD><TD ALIGN=center>"); this.wwrite("[<A HREF=\"" + "javascript:window.opener.Build(" + "'" + this.gReturnItem + "', null, '" + nextYYYY + "', '" + this.gFormat + "'" + ");" + "\">>><\/A>]</TD></TR></TABLE><BR>"); // Get the complete calendar code for each month.. var j; for (i=11; i>=0; i--) { if (isIE) this.wwrite("<DIV ID=\"layer" + i + "\" CLASS=\"lclass" + i + "\">"); else if (isNav) this.wwrite("<LAYER ID=\"layer" + i + "\" CLASS=\"lclass" + i + "\">"); this.gMonth = i; this.gMonthName = Calendar.get_month(this.gMonth); vCode = this.getMonthlyCalendarCode(); this.wwrite(this.gMonthName + "/" + this.gYear + "<BR>"); this.wwrite(vCode); if (isIE) this.wwrite("</DIV>"); else if (isNav) this.wwrite("</LAYER>"); } this.wwrite("</font><BR></body></html>"); this.gWinCal.document.close(); } Calendar.prototype.wwrite = function(wtext) { this.gWinCal.document.writeln(wtext); } Calendar.prototype.wwriteA = function(wtext) { this.gWinCal.document.write(wtext); } Calendar.prototype.cal_header = function() { var vCode = ""; vCode = vCode + "<TR>"; vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='1' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>���</B></FONT></TD>"; vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='1' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>�����</B></FONT></TD>"; vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='1' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>������</B></FONT></TD>"; vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='1' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>������</B></FONT></TD>"; vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='1' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>����</B></FONT></TD>"; vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='1' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>����</B></FONT></TD>"; vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='1' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>���</B></FONT></TD>"; vCode = vCode + "</TR>"; return vCode; } Calendar.prototype.cal_data = function() { var vDate = new Date(); vDate.setDate(1); vDate.setMonth(this.gMonth); vDate.setFullYear(this.gYear); var vFirstDay=vDate.getDay(); var vDay=1; var vLastDay=Calendar.get_daysofmonth(this.gMonth, this.gYear); var vOnLastDay=0; var vCode = ""; /* Get day for the 1st of the requested month/year.. Place as many blank cells before the 1st day of the month as necessary. */ vCode = vCode + "<TR>"; for (i=0; i<vFirstDay; i++) { vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(i) + "><FONT SIZE='1' FACE='" + fontface + "'> </FONT></TD>"; } // Write rest of the 1st week for (j=vFirstDay; j<7; j++) { vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(j) + "><FONT SIZE='1' FACE='" + fontface + "'>" + "<A HREF='#' " + "onClick=\"self.opener.document." + this.gReturnItem + ".value='" + this.format_data(vDay) + "';window.close();\">" + this.format_day(vDay) + "</A>" + "</FONT></TD>"; vDay=vDay + 1; } vCode = vCode + "</TR>"; // Write the rest of the weeks for (k=2; k<7; k++) { vCode = vCode + "<TR>"; for (j=0; j<7; j++) { vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(j) + "><FONT SIZE='1' FACE='" + fontface + "'>" + "<A HREF='#' " + "onClick=\"self.opener.document." + this.gReturnItem + ".value='" + this.format_data(vDay) + "';window.close();\">" + this.format_day(vDay) + "</A>" + "</FONT></TD>"; vDay=vDay + 1; if (vDay > vLastDay) { vOnLastDay = 1; break; } } if (j == 6) vCode = vCode + "</TR>"; if (vOnLastDay == 1) break; } // Fill up the rest of last week with proper blanks, so that we get proper square blocks for (m=1; m<(7-j); m++) { if (this.gYearly) vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(j+m) + "><FONT SIZE='1' FACE='" + fontface + "' COLOR='gray'> </FONT></TD>"; else vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(j+m) + "><FONT SIZE='1' FACE='" + fontface + "' COLOR='gray'>" + m + "</FONT></TD>"; } return vCode; } Calendar.prototype.format_day = function(vday) { var vNowDay = gNow.getDate(); var vNowMonth = gNow.getMonth(); var vNowYear = gNow.getFullYear(); var oDay = (vday.toString().length < 2) ? "0" + vday : vday; var oMon = parseInt(this.gMonth)+1; oMon = (oMon.toString().length < 2) ? "0" + oMon : oMon; var oDate = oDay+"/"+oMon+"/"+this.gYear; // if (TYPE ==1) // { if (vday == vNowDay && this.gMonth == vNowMonth && this.gYear == vNowYear) return ("<FONT FACE=\"verdana\" SIZE=\"1\" COLOR=\"#914848\"><B>" + vday + "</B></FONT>"); else return (vday); /* } else { if (vday == vNowDay && this.gMonth == vNowMonth && this.gYear == vNowYear) return ("<FONT FACE=\"verdana\" SIZE=\"1\" COLOR=\"#914848\"><B>" + convDay(oDate) + "</B></FONT>"); else return (convDay(oDate)); } */ } Calendar.prototype.write_weekend_string = function(vday) { var i; // Return special formatting for the weekend day. for (i=0; i<weekend.length; i++) { if (vday == weekend[i]) return (" BGCOLOR=\"" + weekendColor + "\""); } return ""; } Calendar.prototype.format_data = function(p_day) { var vData; var vMonth = 1 + this.gMonth; vMonth = (vMonth.toString().length < 2) ? "0" + vMonth : vMonth; var vMon = Calendar.get_month(this.gMonth).substr(0,3).toUpperCase(); var vFMon = Calendar.get_month(this.gMonth).toUpperCase(); var vY4 = new String(this.gYear); var vY2 = new String(this.gYear.substr(2,2)); var vDD = (p_day.toString().length < 2) ? "0" + p_day : p_day; switch (this.gFormat) { case "MM\/DD\/YYYY" : vData = vMonth + "\/" + vDD + "\/" + vY4; break; case "MM\/DD\/YY" : vData = vMonth + "\/" + vDD + "\/" + vY2; break; case "MM-DD-YYYY" : vData = vMonth + "-" + vDD + "-" + vY4; break; case "MM-DD-YY" : vData = vMonth + "-" + vDD + "-" + vY2; break; case "DD\/MON\/YYYY" : vData = vDD + "\/" + vMon + "\/" + vY4; break; case "DD\/MON\/YY" : vData = vDD + "\/" + vMon + "\/" + vY2; break; case "DD-MON-YYYY" : vData = vDD + "-" + vMon + "-" + vY4; break; case "DD-MON-YY" : vData = vDD + "-" + vMon + "-" + vY2; break; case "DD\/MONTH\/YYYY" : vData = vDD + "\/" + vFMon + "\/" + vY4; break; case "DD\/MONTH\/YY" : vData = vDD + "\/" + vFMon + "\/" + vY2; break; case "DD-MONTH-YYYY" : vData = vDD + "-" + vFMon + "-" + vY4; break; case "DD-MONTH-YY" : vData = vDD + "-" + vFMon + "-" + vY2; break; case "DD\/MM\/YYYY" : vData = vDD + "\/" + vMonth + "\/" + vY4; break; case "DD\/MM\/YY" : vData = vDD + "\/" + vMonth + "\/" + vY2; break; case "DD-MM-YYYY" : vData = vDD + "-" + vMonth + "-" + vY4; break; case "DD-MM-YY" : vData = vDD + "-" + vMonth + "-" + vY2; break; default : vData = vDD + "\/" + vMonth + "\/" + vY4; } if (TYPE == 2) { vData = convDate(vData); } return vData; } function Build(p_item, p_month, p_year, p_format,type) { var p_WinCal = ggWinCal; gCal = new Calendar(p_item, p_WinCal, p_month, p_year, p_format,type); // Customize your Calendar here.. gCal.gBGColor="white"; gCal.gLinkColor="#27570E"; gCal.gTextColor="#27570E"; gCal.gHeaderColor="#27570E"; // Choose appropriate show function if (gCal.gYearly) gCal.showY(); else gCal.show(); } function show_calendar() { /* p_month : 0-11 for Jan-Dec; 12 for All Months. p_year : 4-digit year p_format: Date format (mm/dd/yyyy, dd/mm/yy, ...) p_item : Return Item. */ p_item = arguments[0]; if (arguments[1] == null) p_month = new String(gNow.getMonth()); else p_month = arguments[1]; if (arguments[2] == "" || arguments[2] == null) p_year = new String(gNow.getFullYear().toString()); else p_year = arguments[2]; if (arguments[3] == null) p_format = "DD/MM/YYYY"; else p_format = arguments[3]; TYPE = arguments[4]; vWinCal = window.open("", "Calendar", "width=232,height=190,status=no,resizable=no,top=200,left=200"); vWinCal.opener = self; ggWinCal = vWinCal; Build(p_item, p_month, p_year, p_format); } /* Yearly Calendar Code Starts here */ function show_yearly_calendar(p_item, p_year, p_format) { // Load the defaults.. if (p_year == null || p_year == "") p_year = new String(gNow.getFullYear().toString()); if (p_format == null || p_format == "") p_format = "DD/MM/YYYY"; var vWinCal = window.open("", "Calendar", "scrollbars=yes"); vWinCal.opener = self; ggWinCal = vWinCal; Build(p_item, null, p_year, p_format); } HI Guys, Could someone help me out; i am checking if return_date is greater than the departure_date. Somehow the date is checking on mm/dd/yyyy format while my form is capturing date on dd/mm/yyyy format. Can someone point out where i can actually change this format. I would like to stick to dd/mm/yyyy format. Here is my code:- <script language="javascript" type="text/javascript"> function doDateCheck() { var depart=new Date(document.getElementById('DPC_date1').value); var return=new Date(document.getElementById('DPC_date2').value); if(eval(return.getTime() )<eval(depart.getTime())) { alert("Return date must be greater then departure date."); return false; } return true; } </script> i need a script that validate date with following options 1: commom validation like mm/dd/yyyy or dd/mm/yyyy 2: if user enter previous date then alert please todays or future date. 3: if user enter invalid format then alert invalid format. 4: if user invalid date then alert its an invalid date. 5: if user enter alphabatic in date field then also alert. HI All, i have a form with 5 date fields, and i need to validate these fields against each other and prevent two date fields from future dates. I have used EPOCH calendar control on my page and set all date fields as read only. The calendar function is called on page load event. I have written a function to compare my dates (comparedates()) and called this function into another function (validateform(this)) which is triggered when the form is submitted. The validateform function first checks for null values and then calls comparedates function. When i test the form, the validate form works well and the form won't submit if there are any missing details, however when it executes the comparedates() function, this is what happens: in FireFox: alerts are popping up, but the page is submitted anyway in IE8 : alerts do not pop up and the page is submitted in both browsers i don't see any javascript error. here is the code i'm using in the page, apart from validateform and compare dates, i have a function to check email and another function to disable/enable text field upon a specific selection from a drop down. These two functions work perfectly, i just included them in the code just to see if it is at all affecting my comparedate() function. please let me know if you would like to also see EPOCH calendar code. Thank you for your help Maryam Code: function getToday() { var date = new Date(); var mm = zeroPadValue(date.getMonth() + 1); var dd = zeroPadValue(date.getDate()); var yyyy = date.getFullYear(); var result = yyyy + "-" + mm + "-" + dd; return result; } function zeroPadValue(value) { if (value < 10) { value = "0" + value; } return value; } function validateForm(form) { var sysDate = new getToday(); var obj=document.createform.nationality; for(var i=0; i < form.elements.length; i++){ if(form.elements[i].value.length == 0 && form.elements[i].name != "submit" && form.elements[i].name !="qualification" && form.elements[i].name !="gender" && form.elements[i].name !="marital" && form.elements[i].name !="cbirth" && form.elements[i].name !="citybirth" && form.elements[i].name !="email" && form.elements[i].name !="pspace" && form.elements[i].name !="paidby" && form.elements[i].name !="visano" && form.elements[i].name !="difcsponsored" && form.elements[i].name !="vissuedate" && form.elements[i].name !="vexpirydate" && form.elements[i].name !="compreg"){ alert('No value entered in '+form.elements[i].title+'.'); form.elements[i].focus(); return false; } } comparedates(); return true; } function comparedates() { var form = document.forms[0]; var curr = new Date(getToday()); var getdob = new Date(document.createform.dob.value); var getpi = new Date(document.createform.pissue.value); var getpe = new Date(document.createform.pexpiry.value); for(var i=0; i < form.elements.length; i++) { if(form.elements[i].name =="dob") { if(getdob > curr) { alert(form.elements[i].title + ' cannot be greater than today\'\s date.'); form.elements[i].focus(); return false; } } if(form.elements[i].name=="pissue") { if(getpi > curr ) { alert(form.elements[i].title+' cannot be greater than today\'\s date.'); form.elements[i].focus(); return false; } if(getpi < getdob) { alert(form.elements[i].title+' cannot be smaller than ' + document.createform.dob.title + '.'); form.elements[i].focus(); return false; } } if(form.elements[i].name=="pexpiry"){ if(getpe < getpi) { alert(form.elements[i].title+' cannot be smaller than ' + document.createform.pissue.title +'.'); form.elements[i].focus(); return false; } if( getpe < getdob) { alert(form.elements[i].title+' cannot be smaller than '+ document.createform.dob.title+'.'); form.elements[i].focus(); return false; } } } } function disableFields(obj){ if(obj.options[obj.selectedIndex].value=="BH" || obj.options[obj.selectedIndex].value=="KW" || obj.options[obj.selectedIndex].value=="OM" || obj.options[obj.selectedIndex].value=="QA" || obj.options[obj.selectedIndex].value=="SA" || obj.options[obj.selectedIndex].value=="AE"){ // alert('true'); document.createform.visano.disabled=true; document.createform.difcsponsored.disabled=true; document.createform.vissuedate.disabled=true; document.createform.vexpirydate.disabled=true; } else { document.createform.visano.disabled=false; document.createform.difcsponsored.disabled=false; document.createform.vissuedate.disabled=false; document.createform.vexpirydate.disabled=false; } } function validateEmail(myemail){ var AtPos = myemail.value.indexOf("@"); var StopPos = myemail.value.lastIndexOf("."); var Message = ""; //var getemail = document.getElementById("txtemail"); if (myemail.value.length !=0){ if (AtPos == -1 || StopPos == -1 || StopPos < AtPos || StopPos - AtPos == 1) { Message = "Not a valid email address"; alert (Message); //myemail.focus(); setTimeout('document.getElementById(\'email\').focus();document.getElementById(\'email\').select();',0); //return false; } else { return true; } } } function callall(){ getCal(); // comparedates(); } Maybe somone can help me out he I am trying to validate two dates, to make sure one comes before another. This is the code I have: Code: function validate_time(fielda, fieldb) { if (fielda < fieldb ) { ErrFields.push("The start date must be before the end date"); return false; } else { return true; } } and it is called using: Code: validate_time(startdate, enddate); This code dosen't work at all, so I guess I am way off. If anyone knows what may be the problem or any suggestions I would apprecate it. Thanks. Hi, Using this script Code: <script language="javascript" type="text/javascript"> function compareDate() { var start = document.beginDate.startdate.value; var end = document.termDate.enddate.value; var stDate = new Date(start); var enDate = new Date(end); var compDate = enDate - stDate; if(compDate >= 0) return true; else { alert("Please correct-end date is before begin date."); return false; } } </script> Have two input boxes for Start Date and End Date. Both boxes have JQuery linked code for datepicker calendar. Want to ensure that end date is >= to start date. Want dates validated on losing focus from end date input (text) box - like this - I guess. Code: <input style="width: 70px" type="text" id="enddate" onblur="function compareDate();" /> The reason I am here is that, of course, what I have is not working. Appreciate your help. Thanks - John Hi all , first let me just say I know incredibly little about JavaScript at all , I'm currently studying PHP however as part of a course and do occasionally use JavaScript here and there My problem is on a register page for example i have a JavaScript Date picker so users can select their D.O.B without me having to worry about if the date is valid ...etc through PHP checking. PHP Code: <tr> <th>Date of Birth :</th> <td input name="dob" id="dob"><?php $thisyear= getdate(); $myCalendar = new tc_calendar("date5", true, false); $myCalendar->setIcon("./images/iconCalendar.gif"); $myCalendar->setDate($thisyear['year'],$thisyear['month'],$thisyear['day']); $myCalendar->setPath("./"); $myCalendar->setYearInterval(1910, ($thisyear['year'])); $myCalendar->dateAllow('1910-05-13', ($thisyear['year']-18) ); $myCalendar->setDateFormat('j F Y'); //$myCalendar->setHeight(350); //$myCalendar->autoSubmit(true, "form1"); $myCalendar->writeScript(); ?></td> </tr> Now in the <head> tag of my page i do i my JavaScript validation , and was wondering what would i have to do for this to work Thus far i've tried .checked/.selected basically anything i can think of but since its not my forte there isn't a lot for me to think of PHP Code: <script type="text/javascript"> function validate(form) { if(!document.form1.agree.checked) { alert("Please check the terms and conditions"); return false; } if(!document.form1.dob.checked) { alert("Please select a date of birth"); return false; } return true; } </script> </script> Now i was wondering is there anyway to check if a valid date was selected ?? if you can offer any help it'd be much appreciated. Hello, I am arranging a validation form checking a start date (DepartureDate) against today's date to verify that it must be later than today's date, I am a newbie on javascript and I have tried various ways, unfortunately I have hit the wall and I need help. [CODE] <SCRIPT LANGUAGE="JAVASCRIPT" SCRIPT TYPE="TEXT/JAVASCRIPT"> function checkForm() { DepartureDate= /^(0[1-9]|[12][0-9]|3[01])[\/](0[1-9]|1[012])[\/](20)\d\d$/ //check if DepartueDate is valid entry var depdate=myform.DepartureDate.value; // get date from keyed text box var prsDepdate= Date.parse(depdate); // convert to date parse var currentDate = new Date();// today's date var now=Date.parse(currentDate);//parsed todays date if (!DepartureDate.test(depdate)) { alert("Departure Date must be entered in numbers in the following format dd/mm/yyyy with the first two year digits being 20yy"); return false; } //validation if departure Date is entered correctly if (prsDepdate<=currentDate) { alert("Departure Date must be later than Today's date!")//comparison if Departure Date is less than today return false; } } </SCRIPT> [CODE] Thanks a lot I'm a fairly new ColdFusion developer and a true Javascript newbie, so gentleness please! I have a CF application that accepts two dates. The first date - Out Date - is required. The second date - Return Date - is optional, but if populated, must be equal to or greater than the Out Date. Here's the screen & code: <script type="text/javascript"> function compareDate() { if(document.editleave.temp_ret_date.value != "01/01/0001") if(document.editleave.temp_ret_date.value < document.editleave.temp_out_date.value) alert("Scheduled Through Date cannot be earlier than the Scheduled Out Date!"); setFormFocus(document.editleave.temp_ret_date); } </script> <cfinput type="datefield" name="temp_out_date" id="temp_out_date" value="#DateFormat(Now(), 'mm/dd/yyyy')#" validate="date" ValidateAt="onBlur,onSubmit" message="Please enter a valid date in MM/DD/CCYY format." size="6" maxlength="10"> <cfinput type="datefield" name="temp_ret_date" id="temp_ret_date" value="01/01/0001" ValidateAt="onBlur,onSubmit" message="Please enter a valid date in MM/DD/CCYY format." onBlur="compareDate();" size="6" maxlength="10"> Everything works fine....EXCEPT...if the Return Date is invalid, I cannot click on the calendar box to select a date (or open another browser session). Basically, IE is locked up until the user manually types in a valid date. This ain't good. I want to be able to trap the error, just like I have, but I still want the calendar selection box to be usable. Is it possible to "reset" the error condition after the intial warning to only trigger on the onSubmit parameter? I have Code: var myresult; var myresult2; var vresult; function validateusername(username) { var validusername = true; // alert(mobilenumber); http.abort(); http.open("GET", "checkusername.asp?username=" + username, true); //alert("here"); http.onreadystatechange = function() { if (http.readyState == 4) { myresult = http.responseText; // alert(myresult); if (myresult == "True") { validusername = true; } else { alert("username exists "); validusername = false; } } } http.send(null); return validusername; } function validatemessage(message) { var validmessage = true; http.abort(); http.open("GET", "checktext.asp?message=" + message, true); http.onreadystatechange = function() { if (http.readyState == 4) { myresult2 = http.responseText; // alert(myresult); if (myresult2 == "True") { validmessage = true; // alert("valid message is true") } else { alert("You cannot put emails or telephone numbers in any of the details fields"); validmessage = false; } } } http.send(null); alert(validmessage); return validmessage; } and then within my validation if (!validateusername(document.getElementById("x_Username").value)) { return false; } and if (!validatemessage(document.getElementById("x_On_Self").value)) { return false; } Now if I just validate one (like just the uername or must the message field then it works but if I leave the validation to both then if one returns false - it causes both to - what am I doing wrong? Code: if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailvalue)) this is a code to validate an email address. My question is.. how do you call this type of validation? Those /^\w+([\.-]?\w+.. i don't really understand how they work. Is there a special term used to describe this? I want to learn how it works. I want to search for tutorials online but i cant think of any desriptive word to use as keyword for google search. I cant find helpful results. Please help. Thanks Hello, I'm still really new to Javascript and need the help of an expert. I found the following script, for a date picker, however, how can it be modified such that the date selected is output into the date format of dd/mm/yyyy, I also don't need the time, so how could I get the chosen date into that format and ignore the time? Code: // Title: Timestamp picker // Description: See the demo at url // URL: http://us.geocities.com/tspicker/ // Script featured on: http://javascriptkit.com/script/script2/timestamp.shtml // Version: 1.0 // Date: 12-05-2001 (mm-dd-yyyy) // Author: Denis Gritcyuk <denis@softcomplex.com>; <tspicker@yahoo.com> // Notes: Permission given to use this script in any kind of applications if // header lines are left unchanged. Feel free to contact the author // for feature requests and/or donations function show_calendar(str_target, str_datetime) { var arr_months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var week_days = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]; var n_weekstart = 1; // day week starts from (normally 0 or 1) var dt_datetime = (str_datetime == null || str_datetime =="" ? new Date() : str2dt(str_datetime)); var dt_prev_month = new Date(dt_datetime); dt_prev_month.setMonth(dt_datetime.getMonth()-1); var dt_next_month = new Date(dt_datetime); dt_next_month.setMonth(dt_datetime.getMonth()+1); var dt_firstday = new Date(dt_datetime); dt_firstday.setDate(1); dt_firstday.setDate(1-(7+dt_firstday.getDay()-n_weekstart)%7); var dt_lastday = new Date(dt_next_month); dt_lastday.setDate(0); // html generation (feel free to tune it for your particular application) // print calendar header var str_buffer = new String ( "<html>\n"+ "<head>\n"+ " <title>Calendar</title>\n"+ "</head>\n"+ "<body bgcolor=\"White\">\n"+ "<table class=\"clsOTable\" cellspacing=\"0\" border=\"0\" width=\"100%\">\n"+ "<tr><td bgcolor=\"#4682B4\">\n"+ "<table cellspacing=\"1\" cellpadding=\"3\" border=\"0\" width=\"100%\">\n"+ "<tr>\n <td bgcolor=\"#4682B4\"><a href=\"javascript:window.opener.show_calendar('"+ str_target+"', '"+ dt2dtstr(dt_prev_month)+"'+document.cal.time.value);\">"+ "<img src=\"prev.gif\" width=\"16\" height=\"16\" border=\"0\""+ " alt=\"previous month\"></a></td>\n"+ " <td bgcolor=\"#4682B4\" colspan=\"5\">"+ "<font color=\"white\" face=\"tahoma, verdana\" size=\"2\">" +arr_months[dt_datetime.getMonth()]+" "+dt_datetime.getFullYear()+"</font></td>\n"+ " <td bgcolor=\"#4682B4\" align=\"right\"><a href=\"javascript:window.opener.show_calendar('" +str_target+"', '"+dt2dtstr(dt_next_month)+"'+document.cal.time.value);\">"+ "<img src=\"next.gif\" width=\"16\" height=\"16\" border=\"0\""+ " alt=\"next month\"></a></td>\n</tr>\n" ); var dt_current_day = new Date(dt_firstday); // print weekdays titles str_buffer += "<tr>\n"; for (var n=0; n<7; n++) str_buffer += " <td bgcolor=\"#87CEFA\">"+ "<font color=\"white\" face=\"tahoma, verdana\" size=\"2\">"+ week_days[(n_weekstart+n)%7]+"</font></td>\n"; // print calendar table str_buffer += "</tr>\n"; while (dt_current_day.getMonth() == dt_datetime.getMonth() || dt_current_day.getMonth() == dt_firstday.getMonth()) { // print row heder str_buffer += "<tr>\n"; for (var n_current_wday=0; n_current_wday<7; n_current_wday++) { if (dt_current_day.getDate() == dt_datetime.getDate() && dt_current_day.getMonth() == dt_datetime.getMonth()) // print current date str_buffer += " <td bgcolor=\"#FFB6C1\" align=\"right\">"; else if (dt_current_day.getDay() == 0 || dt_current_day.getDay() == 6) // weekend days str_buffer += " <td bgcolor=\"#DBEAF5\" align=\"right\">"; else // print working days of current month str_buffer += " <td bgcolor=\"white\" align=\"right\">"; if (dt_current_day.getMonth() == dt_datetime.getMonth()) // print days of current month str_buffer += "<a href=\"javascript:window.opener."+str_target+ ".value='"+dt2dtstr(dt_current_day)+"'+document.cal.time.value; window.close();\">"+ "<font color=\"black\" face=\"tahoma, verdana\" size=\"2\">"; else // print days of other months str_buffer += "<a href=\"javascript:window.opener."+str_target+ ".value='"+dt2dtstr(dt_current_day)+"'+document.cal.time.value; window.close();\">"+ "<font color=\"gray\" face=\"tahoma, verdana\" size=\"2\">"; str_buffer += dt_current_day.getDate()+"</font></a></td>\n"; dt_current_day.setDate(dt_current_day.getDate()+1); } // print row footer str_buffer += "</tr>\n"; } // print calendar footer str_buffer += "<form name=\"cal\">\n<tr><td colspan=\"7\" bgcolor=\"#87CEFA\">"+ "<font color=\"White\" face=\"tahoma, verdana\" size=\"2\">"+ "Time: <input type=\"text\" name=\"time\" value=\""+dt2tmstr(dt_datetime)+ "\" size=\"8\" maxlength=\"8\"></font></td></tr>\n</form>\n" + "</table>\n" + "</tr>\n</td>\n</table>\n" + "</body>\n" + "</html>\n"; var vWinCal = window.open("", "Calendar", "width=200,height=250,status=no,resizable=yes,top=200,left=200"); vWinCal.opener = self; var calc_doc = vWinCal.document; calc_doc.write (str_buffer); calc_doc.close(); } // datetime parsing and formatting routimes. modify them if you wish other datetime format function str2dt (str_datetime) { var re_date = /^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/; if (!re_date.exec(str_datetime)) return alert("Invalid Datetime format: "+ str_datetime); return (new Date (RegExp.$3, RegExp.$2-1, RegExp.$1, RegExp.$4, RegExp.$5, RegExp.$6)); } function dt2dtstr (dt_datetime) { return (new String ( dt_datetime.getDate()+"-"+(dt_datetime.getMonth()+1)+"-"+dt_datetime.getFullYear()+" ")); } function dt2tmstr (dt_datetime) { return (new String ( dt_datetime.getHours()+":"+dt_datetime.getMinutes()+":"+dt_datetime.getSeconds())); } Thanks for everyones help. Cheers, J hello, is there a date format for an existing date? all I see is a var d = new Date(); but i need to format an existing date? thanks! Hey all. I have a simple validation I need to do. I need to just make sure that a Checkbox is checked, and that a Text field has content. Sounds simple but I cannot find any thing that has a check and a text field. Here what I have. Can I modify this script to do this? A Checkbox MUST be checked and Text field MUST be filled out. This currently does the text field fine, but no Checkbox obviously. How can I add a checkbox validation to this? Thats it. Any help is appreciated. Code: <script type="text/javascript"> var textFields = ["digsig"]; function validateForm( ) { var oops = ""; // must initialize this! var form = document.sig; for ( var t = 0; t < textFields.length; ++t ) { var field = form[textFields[t]]; var value = field.value.replace(/^\s+/,"").replace(/\s+$/,""); // trim the input if ( value.length < 1 ) { oops += "You MUST enter your Digital Signature"; } } if ( oops != "" ) { alert("ERROR:" + oops); return false; } } } </script> Not sure if this is possible in javascript: I'm looking for two different dates (bill date and due date) on an invoice that are captured by OCR. If one of them exists, but the other does not, I want the empty field to be 14 days before (or after) the other. For example: if the bill date is 7/27/2010 and the due date was not captured, I want to set the due date as 8/10/2010 (14 days after the bill date). If the due date was captured as 8/10/2010, but the due date is blank, I want to assign the bill date as 7/27/2010 (14 days before the due date). if both dates have values, do nothing. Thanks. Using Adobe Form Javascript validation, how would I do this code for Visual Basic in Javascript (non web) Code: If PurchaseDate.Value > Date Then MsgBox ("PurchaseDate cannot be greater than Today's Date!") Cancel = True End If Something along these lines but this isnt working: Code: If (PurchaseDate.Value > Date) Then { app.alert ("Purchase Date cannot be greater than Today's Date!"); } Thanks Hi, I need to add days to a date in javascript, My requirement is as follows: Date is coming from a textbox. eg:- 26/07/2010 days from this statement var day1=document.getElementById('<%=HiddenDate.ClientID %>').value; an eg:- if the date is 28/01/2012 and days Needed to be added=5 the added date should be 02/02/2012. Can anybody help me? Thanks Jamuna Hello, I really need your help with one. How can I use the following code below to save the date from my popup window datepicker back into a var and relay it back onto its parent page? I can't seem to figure this out: Code: <html> <head> <script> function open_cal() { var str_html = "" + "<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + "<head>\n" + "<meta charset=\"utf-8\">\n" + "<title>CALENDAR</title>\n" + "<link href=\"jq/jquery-ui.css\" rel=\"stylesheet\" type=\"text/css\">\n" + "<script src=\"jq/jquery.min.js\" type=\"text/javascript\"></" + "script>\n" + "<script src=\"jq/jquery-ui.min.js\" type=\"text/javascript\"></" + "script>\n" + "<script src=\"jq/datepicker.js\" type=\"text/javascript\"></" + "script>\n" + "</head>\n" + "<body>\n" + "<div id=\"text\" style=\"font: bold 10pt Tahoma\">Enter Approval Date:</div>\n" + "<div id=\"datepicker\"></div>\n" + "</body>\n" + "</html>" var j = window.open("","CALENDAR","width=200,height=250,status=no,resizable=yes,top=200,left=200") j.opener = self; j.document.write(str_html); } </script> </head> <body> <input onclick="open_cal()" type="button" value="Open" name="B1"> </body> </html> Datepicker.js: Code: $(function() { $( "#datepicker" ).datepicker({ dateFormat: 'dd/mm/yy', onSelect: function(dateText, inst) { alert(dateText) window.close() } }) }); Any help with this is greatly and mostly appreciated. Thanks in advance, Cheers, J I have a drop down menu where people can select a month, day and year. Based on their selection, I want to show them an image. If their selection is >= July 26, 2010 but <= July 25, 2011, show the red image; If their selection is >= July 26, 2011 but <= July 25, 2012, show the white image; If their selection is >= July 26, 2012 but <= July 25, 2013, show the blue image; If their selection is >= July 26, 2013 but <= July 25, 2014, show the yellow image; I don't know how to compare a selected date to a range of dates like this. |