JavaScript - Date Validation
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. 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> 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(); } 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 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> 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 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? 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 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 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. 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 Hi, I've inherited a Form which calculates a future date based on a calculation and then inserts today's date and the future date into a database. The day part of the date is formatted as a number. This is fine, but up to 9 the numbers display in single figures with no leading zeros. I want them to display leading zeros (e.g. 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11... 30, 31) So; 1/12/2010 is NOT wanted 01/12/2010 IS wanted The inherited code originally set the Month names as "Jan", "Feb" etc, and it was easy to kludge these to 01, 02... 12, but I suspect there's a more elgant solution to this as well, this bit of the code works so it's not as vital to neaten this but my database needs dd/mm/yyyy format (it's a third party email program). Code: </script> <script type="text/javascript"> var todaysDate = new Date(); function updateExpiryDate(){ var weeklyMileage = document.getElementById('AvWeeklyMileage').value; var expiryDate; var weeks = 0; var expiryDateString = ''; if (!isNaN(parseInt(weeklyMileage))){ weeks = 700/weeklyMileage; expiryDate = new Date(todaysDate.getTime() + (1000 * 3600 * 24 * 7 * weeks)); var expiryDateString = expiryDate.getDate() + '/' + getMonthString(expiryDate.getMonth()+1) + '/' + expiryDate.getFullYear(); document.getElementById('expiryDate').innerHTML = expiryDateString; document.getElementById('ShoeExpiryDate').value = expiryDateString; } else { document.getElementById('ShoeExpiryDate').value = ''; document.getElementById('expiryDate').innerHTML = 'Please enter a valid weekly average mileage' } } function getMonthString(monthNumber){ var monthString = ""; switch(monthNumber){ case 1: monthString = "01"; break; case 2: monthString = "02"; break; case 3: monthString = "03"; break; case 4: monthString = "04"; break; case 5: monthString = "05"; break; case 6: monthString = "06"; break; case 7: monthString = "07"; break; case 8: monthString = "08"; break; case 9: monthString = "09"; break; case 10: monthString = "10"; break; case 11: monthString = "11"; break; case 12: monthString = "12"; break; default: // do nothing; } return monthString; } function setTodaysDate(){ var todaysDateString = todaysDate.getDate() + '/' + getMonthString(todaysDate.getMonth()+1) + '/' + todaysDate.getFullYear(); document.getElementById('todaysDate').innerHTML =todaysDateString; document.getElementById('DateOfPurchase').value = todaysDateString; } Can someone point me in the right direction please? Hello all, new here Seems like a very nice place to be apart of. I have my website www.gebcn.com. If you view source you will see all that I have done, but more importantly my problem. I have the JS code at the top there and I am unable to W3C validate my HTML because of the JS. I am using XHTML strict and would like to stay using it. The JS I have at the top is my form validation code. I am able to do any validating that I need with this "snippet" of code, I have shrank it from my library version just to use for this newsletter. Until now W3C validating was not important now for some reason it is and I am faced with this problem. I am not a Javascript guy more of a HTML/CSS guy and I can manipulate JS to suit my needs. <problem> I have tried to make this "snippet" of JS code an external file but receive multiple errors with the JS calling for the FORM NAME as it is not on the same page. The form NAME=NEWSLETTER is another problem, as W3C says I am unable to use attribute "NAME" in this location. <problem> I would like to keep the JS close to how it is now as I have a library to use this JS over and over again. Any pointers in the right direction or solutions to my problem would be greatly appreciated. Thanks! Hopefully it is not to hard huh If there is anything anyone needs, the code pasted here, or anything else please let me know. Thanks again! hello there this is in vb script. but i dont where to post it. can any one hlep me out plzz I need to check if the date entered by user is within 5th date from current date. I am trying to do it this way entered date has month and date value Code: sResvDate = 01/24 Set sMaxDays to getdate(5) but get date will give year too. and how do i compare if it less than 5th day or not. Hi folks, i am trying to generate a dynamic datefield with date mask "mm/dd/yyyy" and trying to insert it into Oracle db ...i still got the error ORA invalid month ehich means the date filed is not recognized as date: below is what i am doing : newStartDate = document.createElement( 'INPUT' ); newStartDate.setAttribute('type','Date'); newStartDate.setAttribute('id1','id'+ elementid+elementrow); newStartDate.setAttribute('name','StartDateName'+ elementid+elementrow); newStartDate.size=8; newStartDate.style.backgroundColor= bgc; any help thanks ?? Also i want to add a datepicke to this textbox..how it is posible / other option is to use Jquery datepicker but could not know how to impement it thanks again |